blob: 600dda8b504e4ad48ab4aaece899772b474be1b0 [file] [log] [blame]
Niels Möller9155e492017-10-23 09:22:301/*
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 */
Steve Anton10542f22019-01-11 17:11:0010#ifndef RTC_BASE_REF_COUNTER_H_
11#define RTC_BASE_REF_COUNTER_H_
Niels Möller9155e492017-10-23 09:22:3012
Steve Anton10542f22019-01-11 17:11:0013#include "rtc_base/atomic_ops.h"
14#include "rtc_base/ref_count.h"
Niels Möller9155e492017-10-23 09:22:3015
16namespace webrtc {
17namespace webrtc_impl {
18
19class 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
Karl Wiberga8c73262019-01-14 12:18:3126 // Returns kDroppedLastRef if this call dropped the last reference; the caller
27 // should therefore free the resource protected by the reference counter.
28 // Otherwise, returns kOtherRefsRemained (note that in case of multithreading,
29 // some other caller may have dropped the last reference by the time this call
30 // returns; all we know is that we didn't do it).
Niels Möller9155e492017-10-23 09:22:3031 rtc::RefCountReleaseStatus DecRef() {
32 return (rtc::AtomicOps::Decrement(&ref_count_) == 0)
Yves Gerey665174f2018-06-19 13:03:0533 ? rtc::RefCountReleaseStatus::kDroppedLastRef
34 : rtc::RefCountReleaseStatus::kOtherRefsRemained;
Niels Möller9155e492017-10-23 09:22:3035 }
36
37 // Return whether the reference count is one. If the reference count is used
38 // in the conventional way, a reference count of 1 implies that the current
39 // thread owns the reference and no other thread shares it. This call performs
40 // the test for a reference count of one, and performs the memory barrier
41 // needed for the owning thread to act on the resource protected by the
42 // reference counter, knowing that it has exclusive access.
43 bool HasOneRef() const {
44 return rtc::AtomicOps::AcquireLoad(&ref_count_) == 1;
45 }
46
47 private:
48 volatile int ref_count_;
49};
50
51} // namespace webrtc_impl
52} // namespace webrtc
53
Steve Anton10542f22019-01-11 17:11:0054#endif // RTC_BASE_REF_COUNTER_H_