]> git.ipfire.org Git - thirdparty/squid.git/blob - src/base/Lock.h
Source Format Enforcement (#1234)
[thirdparty/squid.git] / src / base / Lock.h
1 /*
2 * Copyright (C) 1996-2023 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 #ifndef SQUID_SRC_BASE_LOCK_H
10 #define SQUID_SRC_BASE_LOCK_H
11
12 /**
13 * This class provides a tracking counter and presents
14 * lock(), unlock() and LockCount() accessors.
15 *
16 * All locks must be cleared with unlock() before this object
17 * is destroyed.
18 *
19 * Accessors provided by this interface are not private,
20 * to allow class hierarchies.
21 *
22 * Build with -DLOCKCOUNT_DEBUG flag to enable lock debugging.
23 * It is disabled by default due to the cost of debug output.
24 */
25 class Lock
26 {
27 public:
28 Lock():count_(0) {}
29
30 virtual ~Lock() { assert(count_ == 0); }
31
32 /// Register one lock / reference against this object.
33 /// All locks must be cleared before it may be destroyed.
34 void lock() const {
35 #if defined(LOCKCOUNT_DEBUG)
36 debugs(0,1, "Incrementing this " << static_cast<void*>(this) << " from count " << count_);
37 #endif
38 assert(count_ < UINT32_MAX);
39 ++count_;
40 }
41
42 /// Clear one lock / reference against this object.
43 /// All locks must be cleared before it may be destroyed.
44 uint32_t unlock() const {
45 #if defined(LOCKCOUNT_DEBUG)
46 debugs(0,1, "Decrementing this " << static_cast<void*>(this) << " from count " << count_);
47 #endif
48 assert(count_ > 0);
49 return --count_;
50 }
51
52 /// Inspect the current count of references.
53 uint32_t LockCount() const { return count_; }
54
55 private:
56 mutable uint32_t count_; ///< number of references currently being tracked
57 };
58
59 // For clarity we provide some aliases for the tracking mechanisms
60 // using Lock so that we can easily see what type of smart pointers
61 // are to be used for the child object.
62 // NP: CbcPointer<> and RefCount<> pointers should be used consistently
63 // for any given child class type
64
65 /// The locking interface for use on Reference-Counted classes
66 #define RefCountable virtual Lock
67
68 #endif /* SQUID_SRC_BASE_LOCK_H */
69