Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
Loading...
Searching...
No Matches
usage_counter.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2021 Roc Streaming authors
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 */
8
9//! @file roc_core/usage_counter.h
10//! @brief Base class for object with usage counter.
11
12#ifndef ROC_CORE_USAGE_COUNTER_H_
13#define ROC_CORE_USAGE_COUNTER_H_
14
15#include "roc_core/atomic.h"
17#include "roc_core/panic.h"
18
19namespace roc {
20namespace core {
21
22//! Base class for object with usage counter.
23//!
24//! Allows to increment and descrement usage counter of the object. Checks the
25//! counter in destructor and panics if it's non-zero.
26//!
27//! Thread-safe.
28class UsageCounter : public NonCopyable<UsageCounter> {
29public:
31 : counter_(0) {
32 }
33
35 if (!counter_.compare_exchange(0, -1)) {
36 roc_panic("usage counter: attempt to destroy object that is still in use: "
37 "usage_counter=%d",
38 (int)counter_);
39 }
40 }
41
42 //! Check whether usage counter is non-zero.
43 bool is_used() const {
44 const int current_counter = counter_;
45
46 if (current_counter < 0) {
47 roc_panic("usage counter: attempt to access destroyed object");
48 }
49
50 return current_counter > 0;
51 }
52
53 //! Increment usage counter.
54 void acquire_usage() const {
55 const int previous_counter = counter_++;
56
57 if (previous_counter < 0) {
58 roc_panic("usage counter: attempt to call acquire on destroyed object");
59 }
60 }
61
62 //! Decrement usage counter.
63 void release_usage() const {
64 const int previous_counter = counter_--;
65
66 if (previous_counter < 0) {
67 roc_panic("usage counter: attempt to call release on destroyed object");
68 }
69
70 if (previous_counter == 0) {
71 roc_panic("usage counter: attempt to call release without acquire");
72 }
73 }
74
75private:
76 mutable Atomic<int> counter_;
77};
78
79} // namespace core
80} // namespace roc
81
82#endif // ROC_CORE_USAGE_COUNTER_H_
Atomic.
Atomic integer. Provides sequential consistency. For a fine-grained memory order control,...
Definition: atomic.h:26
bool compare_exchange(T exp, T des)
Atomic compare-and-swap.
Definition: atomic.h:44
Base class for non-copyable objects.
Definition: noncopyable.h:23
Base class for object with usage counter.
Definition: usage_counter.h:28
bool is_used() const
Check whether usage counter is non-zero.
Definition: usage_counter.h:43
void acquire_usage() const
Increment usage counter.
Definition: usage_counter.h:54
void release_usage() const
Decrement usage counter.
Definition: usage_counter.h:63
Root namespace.
Non-copyable object.
Panic.
#define roc_panic(...)
Print error message and terminate program gracefully.
Definition: panic.h:50