Niels Möller | 9155e49 | 2017-10-23 11:22:30 +0200 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2017 The WebRTC Project Authors. All rights reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | #ifndef RTC_BASE_REFCOUNTER_H_ |
| 11 | #define RTC_BASE_REFCOUNTER_H_ |
| 12 | |
| 13 | #include "rtc_base/atomicops.h" |
| 14 | #include "rtc_base/refcount.h" |
| 15 | |
| 16 | namespace webrtc { |
| 17 | namespace webrtc_impl { |
| 18 | |
| 19 | class RefCounter { |
| 20 | public: |
| 21 | explicit RefCounter(int ref_count) : ref_count_(ref_count) {} |
| 22 | RefCounter() = delete; |
| 23 | |
| 24 | void IncRef() { rtc::AtomicOps::Increment(&ref_count_); } |
| 25 | |
| 26 | // TODO(nisse): Switch return type to RefCountReleaseStatus? |
| 27 | // Returns true if this was the last reference, and the resource protected by |
| 28 | // the reference counter can be deleted. |
| 29 | rtc::RefCountReleaseStatus DecRef() { |
| 30 | return (rtc::AtomicOps::Decrement(&ref_count_) == 0) |
| 31 | ? rtc::RefCountReleaseStatus::kDroppedLastRef |
| 32 | : rtc::RefCountReleaseStatus::kOtherRefsRemained; |
| 33 | } |
| 34 | |
| 35 | // Return whether the reference count is one. If the reference count is used |
| 36 | // in the conventional way, a reference count of 1 implies that the current |
| 37 | // thread owns the reference and no other thread shares it. This call performs |
| 38 | // the test for a reference count of one, and performs the memory barrier |
| 39 | // needed for the owning thread to act on the resource protected by the |
| 40 | // reference counter, knowing that it has exclusive access. |
| 41 | bool HasOneRef() const { |
| 42 | return rtc::AtomicOps::AcquireLoad(&ref_count_) == 1; |
| 43 | } |
| 44 | |
| 45 | private: |
| 46 | volatile int ref_count_; |
| 47 | }; |
| 48 | |
| 49 | } // namespace webrtc_impl |
| 50 | } // namespace webrtc |
| 51 | |
| 52 | #endif // RTC_BASE_REFCOUNTER_H_ |