Bitcoin Core 31.99.0
P2P Digital Currency
sync.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-present The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef BITCOIN_SYNC_H
7#define BITCOIN_SYNC_H
8
9// This header declares threading primitives compatible with Clang
10// Thread Safety Analysis and provides appropriate annotation macros.
11#include <threadsafety.h> // IWYU pragma: export
12#include <util/macros.h>
13
14#include <cassert>
15#include <condition_variable>
16#include <mutex>
17#include <string>
18#include <thread>
19
21// //
22// THE SIMPLE DEFINITION, EXCLUDING DEBUG CODE //
23// //
25
26/*
27RecursiveMutex mutex;
28 std::recursive_mutex mutex;
29
30LOCK(mutex);
31 std::unique_lock<std::recursive_mutex> criticalblock(mutex);
32
33LOCK2(mutex1, mutex2);
34 std::unique_lock<std::recursive_mutex> criticalblock1(mutex1);
35 std::unique_lock<std::recursive_mutex> criticalblock2(mutex2);
36
37TRY_LOCK(mutex, name);
38 std::unique_lock<std::recursive_mutex> name(mutex, std::try_to_lock_t);
39 */
40
42// //
43// THE ACTUAL IMPLEMENTATION //
44// //
46
47#ifdef DEBUG_LOCKORDER
48template <typename MutexType>
49void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false);
50void LeaveCritical();
51void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line);
52template <typename MutexType>
53void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs);
54template <typename MutexType>
55void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs);
56void DeleteLock(void* cs);
57bool LockStackEmpty();
58
64extern bool g_debug_lockorder_abort;
65#else
66template <typename MutexType>
67inline void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false) {}
68inline void LeaveCritical() {}
69inline void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) {}
70template <typename MutexType>
71inline void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs) {}
72template <typename MutexType>
73void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs) {}
74inline void DeleteLock(void* cs) {}
75inline bool LockStackEmpty() { return true; }
76#endif
77
78/*
79 * Called when a mutex fails to lock immediately because it is held by another
80 * thread, or spuriously. Responsible for locking the lock before returning.
81 */
82#ifdef DEBUG_LOCKCONTENTION
83
84template <typename LockType>
85void ContendedLock(std::string_view name, std::string_view file, int nLine, LockType& lock);
86#endif
87
92template <typename PARENT>
93class LOCKABLE AnnotatedMixin : public PARENT
94{
95public:
97 DeleteLock((void*)this);
98 }
99
101 {
102 PARENT::lock();
103 }
104
106 {
107 PARENT::unlock();
108 }
109
111 {
112 return PARENT::try_lock();
113 }
114
115 using unique_lock = std::unique_lock<PARENT>;
116#ifdef __clang__
120 const AnnotatedMixin& operator!() const { return *this; }
121#endif // __clang__
122};
123
129
132
142class GlobalMutex : public Mutex { };
143
144#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
145
146inline void AssertLockNotHeldInline(const char* name, const char* file, int line, Mutex* cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) { AssertLockNotHeldInternal(name, file, line, cs); }
147inline void AssertLockNotHeldInline(const char* name, const char* file, int line, RecursiveMutex* cs) LOCKS_EXCLUDED(cs) { AssertLockNotHeldInternal(name, file, line, cs); }
148inline void AssertLockNotHeldInline(const char* name, const char* file, int line, GlobalMutex* cs) LOCKS_EXCLUDED(cs) { AssertLockNotHeldInternal(name, file, line, cs); }
149#define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs)
150
152template <typename MutexType>
153class SCOPED_LOCKABLE UniqueLock : public MutexType::unique_lock
154{
155private:
156 using Base = typename MutexType::unique_lock;
157
158 void Enter(const char* pszName, const char* pszFile, int nLine)
159 {
160 EnterCritical(pszName, pszFile, nLine, Base::mutex());
161#ifdef DEBUG_LOCKCONTENTION
162 if (!Base::try_lock()) {
163 ContendedLock(pszName, pszFile, nLine, static_cast<Base&>(*this));
164 }
165#else
166 Base::lock();
167#endif
168 }
169
170 bool TryEnter(const char* pszName, const char* pszFile, int nLine)
171 {
172 EnterCritical(pszName, pszFile, nLine, Base::mutex(), true);
173 if (Base::try_lock()) {
174 return true;
175 }
177 return false;
178 }
179
180public:
181 UniqueLock(MutexType& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(mutexIn) : Base(mutexIn, std::defer_lock)
182 {
183 if (fTry)
184 TryEnter(pszName, pszFile, nLine);
185 else
186 Enter(pszName, pszFile, nLine);
187 }
188
189 UniqueLock(MutexType* pmutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
190 {
191 if (!pmutexIn) return;
192
193 *static_cast<Base*>(this) = Base(*pmutexIn, std::defer_lock);
194 if (fTry)
195 TryEnter(pszName, pszFile, nLine);
196 else
197 Enter(pszName, pszFile, nLine);
198 }
199
201 {
202 if (Base::owns_lock())
204 }
205
206 operator bool()
207 {
208 return Base::owns_lock();
209 }
210
211protected:
212 // needed for reverse_lock
213 UniqueLock() = default;
214
215public:
220 public:
221 explicit reverse_lock(UniqueLock& _lock, const MutexType& mutex, const char* _guardname, const char* _file, int _line) UNLOCK_FUNCTION(mutex) : lock(_lock), file(_file), line(_line) {
222 // Ensure that mutex passed back for thread-safety analysis is indeed the original
223 assert(std::addressof(mutex) == lock.mutex());
224
225 CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line);
226 lock.unlock();
228 lock.swap(templock);
229 }
230
232 templock.swap(lock);
233 EnterCritical(lockname.c_str(), file.c_str(), line, lock.mutex());
234 lock.lock();
235 }
236
237 private:
240
243 std::string lockname;
244 const std::string file;
245 const int line;
246 };
247 friend class reverse_lock;
248};
249
250// clang's thread-safety analyzer is unable to deal with aliases of mutexes, so
251// it is not possible to use the lock's copy of the mutex for that purpose.
252// Instead, the original mutex needs to be passed back to the reverse_lock for
253// the sake of thread-safety analysis, but it is not actually used otherwise.
254#define REVERSE_LOCK(g, cs) typename std::decay<decltype(g)>::type::reverse_lock UNIQUE_NAME(revlock)(g, cs, #cs, __FILE__, __LINE__)
255
256// When locking a Mutex, require negative capability to ensure the lock
257// is not already held
260
261// When locking a GlobalMutex or RecursiveMutex, just check it is not
262// locked in the surrounding scope.
263template <typename MutexType>
264inline MutexType& MaybeCheckNotHeld(MutexType& m) LOCKS_EXCLUDED(m) LOCK_RETURNED(m) { return m; }
265template <typename MutexType>
266inline MutexType* MaybeCheckNotHeld(MutexType* m) LOCKS_EXCLUDED(m) LOCK_RETURNED(m) { return m; }
267
268#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
269#define LOCK2(cs1, cs2) \
270 UniqueLock criticalblock1(MaybeCheckNotHeld(cs1), #cs1, __FILE__, __LINE__); \
271 UniqueLock criticalblock2(MaybeCheckNotHeld(cs2), #cs2, __FILE__, __LINE__)
272#define LOCK_ARGS(cs) MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__
273#define TRY_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs), true)
274#define WAIT_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs))
275
299#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
300
301#endif // BITCOIN_SYNC_H
static void pool cs
Template mixin that adds -Wthread-safety locking annotations and lock order checking to a subset of t...
Definition: sync.h:94
~AnnotatedMixin()
Definition: sync.h:96
std::unique_lock< PARENT > unique_lock
Definition: sync.h:115
bool try_lock() EXCLUSIVE_TRYLOCK_FUNCTION(true)
Definition: sync.h:110
void unlock() UNLOCK_FUNCTION()
Definition: sync.h:105
void lock() EXCLUSIVE_LOCK_FUNCTION()
Definition: sync.h:100
(Un)serialize a number as raw byte or 2 hexadecimal chars.
Different type to mark Mutex at global scope.
Definition: sync.h:142
An RAII-style reverse lock.
Definition: sync.h:219
UniqueLock & lock
Definition: sync.h:241
const std::string file
Definition: sync.h:244
~reverse_lock() UNLOCK_FUNCTION()
Definition: sync.h:231
reverse_lock(UniqueLock &_lock, const MutexType &mutex, const char *_guardname, const char *_file, int _line) UNLOCK_FUNCTION(mutex)
Definition: sync.h:221
std::string lockname
Definition: sync.h:243
reverse_lock(reverse_lock const &)
reverse_lock & operator=(reverse_lock const &)
UniqueLock templock
Definition: sync.h:242
Wrapper around std::unique_lock style lock for MutexType.
Definition: sync.h:154
~UniqueLock() UNLOCK_FUNCTION()
Definition: sync.h:200
bool TryEnter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:170
void Enter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:158
UniqueLock()=default
UniqueLock(MutexType &mutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(mutexIn)
Definition: sync.h:181
UniqueLock(MutexType *pmutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
Definition: sync.h:189
Definition: common.h:30
const char * name
Definition: rest.cpp:49
void AssertLockHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: sync.h:71
void AssertLockNotHeldInline(const char *name, const char *file, int line, Mutex *cs) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: sync.h:146
void EnterCritical(const char *pszName, const char *pszFile, int nLine, MutexType *cs, bool fTry=false)
Definition: sync.h:67
void DeleteLock(void *cs)
Definition: sync.h:74
void CheckLastCritical(void *cs, std::string &lockname, const char *guardname, const char *file, int line)
Definition: sync.h:69
void LeaveCritical()
Definition: sync.h:68
bool LockStackEmpty()
Definition: sync.h:75
Mutex & MaybeCheckNotHeld(Mutex &cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) LOCK_RETURNED(cs)
Definition: sync.h:258
void AssertLockNotHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) LOCKS_EXCLUDED(cs)
Definition: sync.h:73
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define EXCLUSIVE_TRYLOCK_FUNCTION(...)
Definition: threadsafety.h:43
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
#define EXCLUSIVE_LOCK_FUNCTION(...)
Definition: threadsafety.h:41
#define SCOPED_LOCKABLE
Definition: threadsafety.h:36
#define LOCKABLE
Definition: threadsafety.h:35
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
#define UNLOCK_FUNCTION(...)
Definition: threadsafety.h:45
assert(!tx.IsCoinBase())