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 */
43
45// //
46// THE ACTUAL IMPLEMENTATION //
47// //
49
50#ifdef DEBUG_LOCKORDER
51template <typename MutexType>
52void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false);
53void LeaveCritical();
54void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line);
55template <typename MutexType>
56void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs);
57template <typename MutexType>
58void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs);
59void DeleteLock(void* cs);
60bool LockStackEmpty();
61
67extern bool g_debug_lockorder_abort;
68#else
69template <typename MutexType>
70inline void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false) {}
71inline void LeaveCritical() {}
72inline void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) {}
73template <typename MutexType>
74inline void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs) {}
75template <typename MutexType>
76void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs) {}
77inline void DeleteLock(void* cs) {}
78inline bool LockStackEmpty() { return true; }
79#endif
80
85template <typename PARENT>
86class LOCKABLE AnnotatedMixin : public PARENT
87{
88public:
90 DeleteLock((void*)this);
91 }
92
94 {
95 PARENT::lock();
96 }
97
99 {
100 PARENT::unlock();
101 }
102
104 {
105 return PARENT::try_lock();
106 }
107
108 using unique_lock = std::unique_lock<PARENT>;
109#ifdef __clang__
113 const AnnotatedMixin& operator!() const { return *this; }
114#endif // __clang__
115};
116
122
125
135class GlobalMutex : public Mutex { };
136
137#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
138
139inline void AssertLockNotHeldInline(const char* name, const char* file, int line, Mutex* cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) { AssertLockNotHeldInternal(name, file, line, cs); }
140inline void AssertLockNotHeldInline(const char* name, const char* file, int line, RecursiveMutex* cs) LOCKS_EXCLUDED(cs) { AssertLockNotHeldInternal(name, file, line, cs); }
141inline void AssertLockNotHeldInline(const char* name, const char* file, int line, GlobalMutex* cs) LOCKS_EXCLUDED(cs) { AssertLockNotHeldInternal(name, file, line, cs); }
142#define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs)
143
145template <typename MutexType>
146class SCOPED_LOCKABLE UniqueLock : public MutexType::unique_lock
147{
148private:
149 using Base = typename MutexType::unique_lock;
150
151 void Enter(const char* pszName, const char* pszFile, int nLine)
152 {
153 EnterCritical(pszName, pszFile, nLine, Base::mutex());
154#ifdef DEBUG_LOCKCONTENTION
155 if (Base::try_lock()) return;
156 LOG_TIME_MICROS_WITH_CATEGORY(strprintf("lock contention %s, %s:%d", pszName, pszFile, nLine), BCLog::LOCK);
157#endif
158 Base::lock();
159 }
160
161 bool TryEnter(const char* pszName, const char* pszFile, int nLine)
162 {
163 EnterCritical(pszName, pszFile, nLine, Base::mutex(), true);
164 if (Base::try_lock()) {
165 return true;
166 }
168 return false;
169 }
170
171public:
172 UniqueLock(MutexType& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(mutexIn) : Base(mutexIn, std::defer_lock)
173 {
174 if (fTry)
175 TryEnter(pszName, pszFile, nLine);
176 else
177 Enter(pszName, pszFile, nLine);
178 }
179
180 UniqueLock(MutexType* pmutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
181 {
182 if (!pmutexIn) return;
183
184 *static_cast<Base*>(this) = Base(*pmutexIn, std::defer_lock);
185 if (fTry)
186 TryEnter(pszName, pszFile, nLine);
187 else
188 Enter(pszName, pszFile, nLine);
189 }
190
192 {
193 if (Base::owns_lock())
195 }
196
197 operator bool()
198 {
199 return Base::owns_lock();
200 }
201
202protected:
203 // needed for reverse_lock
204 UniqueLock() = default;
205
206public:
211 public:
212 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) {
213 // Ensure that mutex passed back for thread-safety analysis is indeed the original
214 assert(std::addressof(mutex) == lock.mutex());
215
216 CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line);
217 lock.unlock();
219 lock.swap(templock);
220 }
221
223 templock.swap(lock);
224 EnterCritical(lockname.c_str(), file.c_str(), line, lock.mutex());
225 lock.lock();
226 }
227
228 private:
231
234 std::string lockname;
235 const std::string file;
236 const int line;
237 };
238 friend class reverse_lock;
239};
240
241// clang's thread-safety analyzer is unable to deal with aliases of mutexes, so
242// it is not possible to use the lock's copy of the mutex for that purpose.
243// Instead, the original mutex needs to be passed back to the reverse_lock for
244// the sake of thread-safety analysis, but it is not actually used otherwise.
245#define REVERSE_LOCK(g, cs) typename std::decay<decltype(g)>::type::reverse_lock UNIQUE_NAME(revlock)(g, cs, #cs, __FILE__, __LINE__)
246
247// When locking a Mutex, require negative capability to ensure the lock
248// is not already held
251
252// When locking a GlobalMutex or RecursiveMutex, just check it is not
253// locked in the surrounding scope.
254template <typename MutexType>
255inline MutexType& MaybeCheckNotHeld(MutexType& m) LOCKS_EXCLUDED(m) LOCK_RETURNED(m) { return m; }
256template <typename MutexType>
257inline MutexType* MaybeCheckNotHeld(MutexType* m) LOCKS_EXCLUDED(m) LOCK_RETURNED(m) { return m; }
258
259#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
260#define LOCK2(cs1, cs2) \
261 UniqueLock criticalblock1(MaybeCheckNotHeld(cs1), #cs1, __FILE__, __LINE__); \
262 UniqueLock criticalblock2(MaybeCheckNotHeld(cs2), #cs2, __FILE__, __LINE__)
263#define LOCK_ARGS(cs) MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__
264#define TRY_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs), true)
265#define WAIT_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs))
266
290#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
291
292#endif // BITCOIN_SYNC_H
Template mixin that adds -Wthread-safety locking annotations and lock order checking to a subset of t...
Definition: sync.h:87
~AnnotatedMixin()
Definition: sync.h:89
std::unique_lock< PARENT > unique_lock
Definition: sync.h:108
bool try_lock() EXCLUSIVE_TRYLOCK_FUNCTION(true)
Definition: sync.h:103
void unlock() UNLOCK_FUNCTION()
Definition: sync.h:98
void lock() EXCLUSIVE_LOCK_FUNCTION()
Definition: sync.h:93
(Un)serialize a number as raw byte or 2 hexadecimal chars.
Different type to mark Mutex at global scope.
Definition: sync.h:135
An RAII-style reverse lock.
Definition: sync.h:210
UniqueLock & lock
Definition: sync.h:232
const std::string file
Definition: sync.h:235
~reverse_lock() UNLOCK_FUNCTION()
Definition: sync.h:222
reverse_lock(UniqueLock &_lock, const MutexType &mutex, const char *_guardname, const char *_file, int _line) UNLOCK_FUNCTION(mutex)
Definition: sync.h:212
std::string lockname
Definition: sync.h:234
reverse_lock(reverse_lock const &)
reverse_lock & operator=(reverse_lock const &)
UniqueLock templock
Definition: sync.h:233
Wrapper around std::unique_lock style lock for MutexType.
Definition: sync.h:147
~UniqueLock() UNLOCK_FUNCTION()
Definition: sync.h:191
bool TryEnter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:161
void Enter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:151
UniqueLock()=default
UniqueLock(MutexType &mutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(mutexIn)
Definition: sync.h:172
UniqueLock(MutexType *pmutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
Definition: sync.h:180
static void pool cs
const char * name
Definition: rest.cpp:50
void AssertLockHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: sync.h:74
void AssertLockNotHeldInline(const char *name, const char *file, int line, Mutex *cs) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: sync.h:139
void EnterCritical(const char *pszName, const char *pszFile, int nLine, MutexType *cs, bool fTry=false)
Definition: sync.h:70
void DeleteLock(void *cs)
Definition: sync.h:77
#define LOCK(cs)
Definition: sync.h:259
void CheckLastCritical(void *cs, std::string &lockname, const char *guardname, const char *file, int line)
Definition: sync.h:72
void LeaveCritical()
Definition: sync.h:71
bool LockStackEmpty()
Definition: sync.h:78
Mutex & MaybeCheckNotHeld(Mutex &cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) LOCK_RETURNED(cs)
Definition: sync.h:249
void AssertLockNotHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) LOCKS_EXCLUDED(cs)
Definition: sync.h:76
#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())