Bitcoin Core 29.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-2022 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#ifdef DEBUG_LOCKCONTENTION
10#include <logging.h>
11#include <logging/timer.h>
12#endif
13
14#include <threadsafety.h> // IWYU pragma: export
15#include <util/macros.h>
16
17#include <cassert>
18#include <condition_variable>
19#include <mutex>
20#include <string>
21#include <thread>
22
24// //
25// THE SIMPLE DEFINITION, EXCLUDING DEBUG CODE //
26// //
28
29/*
30RecursiveMutex mutex;
31 std::recursive_mutex mutex;
32
33LOCK(mutex);
34 std::unique_lock<std::recursive_mutex> criticalblock(mutex);
35
36LOCK2(mutex1, mutex2);
37 std::unique_lock<std::recursive_mutex> criticalblock1(mutex1);
38 std::unique_lock<std::recursive_mutex> criticalblock2(mutex2);
39
40TRY_LOCK(mutex, name);
41 std::unique_lock<std::recursive_mutex> name(mutex, std::try_to_lock_t);
42
43ENTER_CRITICAL_SECTION(mutex); // no RAII
44 mutex.lock();
45
46LEAVE_CRITICAL_SECTION(mutex); // no RAII
47 mutex.unlock();
48 */
49
51// //
52// THE ACTUAL IMPLEMENTATION //
53// //
55
56#ifdef DEBUG_LOCKORDER
57template <typename MutexType>
58void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false);
59void LeaveCritical();
60void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line);
61template <typename MutexType>
62void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs);
63template <typename MutexType>
64void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs);
65void DeleteLock(void* cs);
66bool LockStackEmpty();
67
73extern bool g_debug_lockorder_abort;
74#else
75template <typename MutexType>
76inline void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false) {}
77inline void LeaveCritical() {}
78inline void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) {}
79template <typename MutexType>
80inline void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs) {}
81template <typename MutexType>
82void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs) {}
83inline void DeleteLock(void* cs) {}
84inline bool LockStackEmpty() { return true; }
85#endif
86
91template <typename PARENT>
92class LOCKABLE AnnotatedMixin : public PARENT
93{
94public:
96 DeleteLock((void*)this);
97 }
98
100 {
101 PARENT::lock();
102 }
103
105 {
106 PARENT::unlock();
107 }
108
110 {
111 return PARENT::try_lock();
112 }
113
114 using unique_lock = std::unique_lock<PARENT>;
115#ifdef __clang__
119 const AnnotatedMixin& operator!() const { return *this; }
120#endif // __clang__
121};
122
128
131
141class GlobalMutex : public Mutex { };
142
143#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
144
145inline void AssertLockNotHeldInline(const char* name, const char* file, int line, Mutex* cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) { AssertLockNotHeldInternal(name, file, line, cs); }
146inline void AssertLockNotHeldInline(const char* name, const char* file, int line, RecursiveMutex* cs) LOCKS_EXCLUDED(cs) { AssertLockNotHeldInternal(name, file, line, cs); }
147inline void AssertLockNotHeldInline(const char* name, const char* file, int line, GlobalMutex* cs) LOCKS_EXCLUDED(cs) { AssertLockNotHeldInternal(name, file, line, cs); }
148#define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs)
149
151template <typename MutexType>
152class SCOPED_LOCKABLE UniqueLock : public MutexType::unique_lock
153{
154private:
155 using Base = typename MutexType::unique_lock;
156
157 void Enter(const char* pszName, const char* pszFile, int nLine)
158 {
159 EnterCritical(pszName, pszFile, nLine, Base::mutex());
160#ifdef DEBUG_LOCKCONTENTION
161 if (Base::try_lock()) return;
162 LOG_TIME_MICROS_WITH_CATEGORY(strprintf("lock contention %s, %s:%d", pszName, pszFile, nLine), BCLog::LOCK);
163#endif
164 Base::lock();
165 }
166
167 bool TryEnter(const char* pszName, const char* pszFile, int nLine)
168 {
169 EnterCritical(pszName, pszFile, nLine, Base::mutex(), true);
170 if (Base::try_lock()) {
171 return true;
172 }
174 return false;
175 }
176
177public:
178 UniqueLock(MutexType& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(mutexIn) : Base(mutexIn, std::defer_lock)
179 {
180 if (fTry)
181 TryEnter(pszName, pszFile, nLine);
182 else
183 Enter(pszName, pszFile, nLine);
184 }
185
186 UniqueLock(MutexType* pmutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
187 {
188 if (!pmutexIn) return;
189
190 *static_cast<Base*>(this) = Base(*pmutexIn, std::defer_lock);
191 if (fTry)
192 TryEnter(pszName, pszFile, nLine);
193 else
194 Enter(pszName, pszFile, nLine);
195 }
196
198 {
199 if (Base::owns_lock())
201 }
202
203 operator bool()
204 {
205 return Base::owns_lock();
206 }
207
208protected:
209 // needed for reverse_lock
210 UniqueLock() = default;
211
212public:
217 public:
218 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) {
219 // Ensure that mutex passed back for thread-safety analysis is indeed the original
220 assert(std::addressof(mutex) == lock.mutex());
221
222 CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line);
223 lock.unlock();
225 lock.swap(templock);
226 }
227
229 templock.swap(lock);
230 EnterCritical(lockname.c_str(), file.c_str(), line, lock.mutex());
231 lock.lock();
232 }
233
234 private:
237
240 std::string lockname;
241 const std::string file;
242 const int line;
243 };
244 friend class reverse_lock;
245};
246
247// clang's thread-safety analyzer is unable to deal with aliases of mutexes, so
248// it is not possible to use the lock's copy of the mutex for that purpose.
249// Instead, the original mutex needs to be passed back to the reverse_lock for
250// the sake of thread-safety analysis, but it is not actually used otherwise.
251#define REVERSE_LOCK(g, cs) typename std::decay<decltype(g)>::type::reverse_lock UNIQUE_NAME(revlock)(g, cs, #g, __FILE__, __LINE__)
252
253// When locking a Mutex, require negative capability to ensure the lock
254// is not already held
257
258// When locking a GlobalMutex or RecursiveMutex, just check it is not
259// locked in the surrounding scope.
260template <typename MutexType>
261inline MutexType& MaybeCheckNotHeld(MutexType& m) LOCKS_EXCLUDED(m) LOCK_RETURNED(m) { return m; }
262template <typename MutexType>
263inline MutexType* MaybeCheckNotHeld(MutexType* m) LOCKS_EXCLUDED(m) LOCK_RETURNED(m) { return m; }
264
265#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
266#define LOCK2(cs1, cs2) \
267 UniqueLock criticalblock1(MaybeCheckNotHeld(cs1), #cs1, __FILE__, __LINE__); \
268 UniqueLock criticalblock2(MaybeCheckNotHeld(cs2), #cs2, __FILE__, __LINE__)
269#define LOCK_ARGS(cs) MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__
270#define TRY_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs), true)
271#define WAIT_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs))
272
273#define ENTER_CRITICAL_SECTION(cs) \
274 { \
275 EnterCritical(#cs, __FILE__, __LINE__, &cs); \
276 (cs).lock(); \
277 }
278
279#define LEAVE_CRITICAL_SECTION(cs) \
280 { \
281 std::string lockname; \
282 CheckLastCritical((void*)(&cs), lockname, #cs, __FILE__, __LINE__); \
283 (cs).unlock(); \
284 LeaveCritical(); \
285 }
286
310#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
311
312#endif // BITCOIN_SYNC_H
Template mixin that adds -Wthread-safety locking annotations and lock order checking to a subset of t...
Definition: sync.h:93
~AnnotatedMixin()
Definition: sync.h:95
std::unique_lock< PARENT > unique_lock
Definition: sync.h:114
bool try_lock() EXCLUSIVE_TRYLOCK_FUNCTION(true)
Definition: sync.h:109
void unlock() UNLOCK_FUNCTION()
Definition: sync.h:104
void lock() EXCLUSIVE_LOCK_FUNCTION()
Definition: sync.h:99
(Un)serialize a number as raw byte or 2 hexadecimal chars.
Different type to mark Mutex at global scope.
Definition: sync.h:141
An RAII-style reverse lock.
Definition: sync.h:216
UniqueLock & lock
Definition: sync.h:238
const std::string file
Definition: sync.h:241
~reverse_lock() UNLOCK_FUNCTION()
Definition: sync.h:228
reverse_lock(UniqueLock &_lock, const MutexType &mutex, const char *_guardname, const char *_file, int _line) UNLOCK_FUNCTION(mutex)
Definition: sync.h:218
std::string lockname
Definition: sync.h:240
reverse_lock(reverse_lock const &)
reverse_lock & operator=(reverse_lock const &)
UniqueLock templock
Definition: sync.h:239
Wrapper around std::unique_lock style lock for MutexType.
Definition: sync.h:153
~UniqueLock() UNLOCK_FUNCTION()
Definition: sync.h:197
bool TryEnter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:167
void Enter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:157
UniqueLock()=default
UniqueLock(MutexType &mutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(mutexIn)
Definition: sync.h:178
UniqueLock(MutexType *pmutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
Definition: sync.h:186
static void pool cs
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:80
void AssertLockNotHeldInline(const char *name, const char *file, int line, Mutex *cs) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: sync.h:145
void EnterCritical(const char *pszName, const char *pszFile, int nLine, MutexType *cs, bool fTry=false)
Definition: sync.h:76
void DeleteLock(void *cs)
Definition: sync.h:83
#define LOCK(cs)
Definition: sync.h:265
void CheckLastCritical(void *cs, std::string &lockname, const char *guardname, const char *file, int line)
Definition: sync.h:78
void LeaveCritical()
Definition: sync.h:77
bool LockStackEmpty()
Definition: sync.h:84
Mutex & MaybeCheckNotHeld(Mutex &cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) LOCK_RETURNED(cs)
Definition: sync.h:255
void AssertLockNotHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) LOCKS_EXCLUDED(cs)
Definition: sync.h:82
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
#define EXCLUSIVE_TRYLOCK_FUNCTION(...)
Definition: threadsafety.h:45
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:50
#define EXCLUSIVE_LOCK_FUNCTION(...)
Definition: threadsafety.h:43
#define SCOPED_LOCKABLE
Definition: threadsafety.h:38
#define LOCKABLE
Definition: threadsafety.h:37
#define LOCK_RETURNED(x)
Definition: threadsafety.h:49
#define UNLOCK_FUNCTION(...)
Definition: threadsafety.h:47
#define LOG_TIME_MICROS_WITH_CATEGORY(end_msg, log_category)
Definition: timer.h:101
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
assert(!tx.IsCoinBase())