Bitcoin Core  24.1.0
P2P Digital Currency
sync.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 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>
15 #include <util/macros.h>
16 
17 #include <condition_variable>
18 #include <mutex>
19 #include <string>
20 #include <thread>
21 
23 // //
24 // THE SIMPLE DEFINITION, EXCLUDING DEBUG CODE //
25 // //
27 
28 /*
29 RecursiveMutex mutex;
30  std::recursive_mutex mutex;
31 
32 LOCK(mutex);
33  std::unique_lock<std::recursive_mutex> criticalblock(mutex);
34 
35 LOCK2(mutex1, mutex2);
36  std::unique_lock<std::recursive_mutex> criticalblock1(mutex1);
37  std::unique_lock<std::recursive_mutex> criticalblock2(mutex2);
38 
39 TRY_LOCK(mutex, name);
40  std::unique_lock<std::recursive_mutex> name(mutex, std::try_to_lock_t);
41 
42 ENTER_CRITICAL_SECTION(mutex); // no RAII
43  mutex.lock();
44 
45 LEAVE_CRITICAL_SECTION(mutex); // no RAII
46  mutex.unlock();
47  */
48 
50 // //
51 // THE ACTUAL IMPLEMENTATION //
52 // //
54 
55 #ifdef DEBUG_LOCKORDER
56 template <typename MutexType>
57 void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false);
58 void LeaveCritical();
59 void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line);
60 std::string LocksHeld();
61 template <typename MutexType>
62 void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs);
63 template <typename MutexType>
64 void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs);
65 void DeleteLock(void* cs);
66 bool LockStackEmpty();
67 
73 extern bool g_debug_lockorder_abort;
74 #else
75 template <typename MutexType>
76 inline void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false) {}
77 inline void LeaveCritical() {}
78 inline void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) {}
79 template <typename MutexType>
80 inline void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs) {}
81 template <typename MutexType>
82 void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs) {}
83 inline void DeleteLock(void* cs) {}
84 inline bool LockStackEmpty() { return true; }
85 #endif
86 
91 template <typename PARENT>
92 class LOCKABLE AnnotatedMixin : public PARENT
93 {
94 public:
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 UniqueLock = std::unique_lock<PARENT>;
115 #ifdef __clang__
116  const AnnotatedMixin& operator!() const { return *this; }
120 #endif // __clang__
121 };
122 
128 
131 
141 class GlobalMutex : public Mutex { };
142 
143 #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
144 
145 inline void AssertLockNotHeldInline(const char* name, const char* file, int line, Mutex* cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) { AssertLockNotHeldInternal(name, file, line, cs); }
146 inline void AssertLockNotHeldInline(const char* name, const char* file, int line, RecursiveMutex* cs) LOCKS_EXCLUDED(cs) { AssertLockNotHeldInternal(name, file, line, cs); }
147 inline 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 
151 template <typename Mutex, typename Base = typename Mutex::UniqueLock>
152 class SCOPED_LOCKABLE UniqueLock : public Base
153 {
154 private:
155  void Enter(const char* pszName, const char* pszFile, int nLine)
156  {
157  EnterCritical(pszName, pszFile, nLine, Base::mutex());
158 #ifdef DEBUG_LOCKCONTENTION
159  if (Base::try_lock()) return;
160  LOG_TIME_MICROS_WITH_CATEGORY(strprintf("lock contention %s, %s:%d", pszName, pszFile, nLine), BCLog::LOCK);
161 #endif
162  Base::lock();
163  }
164 
165  bool TryEnter(const char* pszName, const char* pszFile, int nLine)
166  {
167  EnterCritical(pszName, pszFile, nLine, Base::mutex(), true);
168  Base::try_lock();
169  if (!Base::owns_lock()) {
170  LeaveCritical();
171  }
172  return Base::owns_lock();
173  }
174 
175 public:
176  UniqueLock(Mutex& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(mutexIn) : Base(mutexIn, std::defer_lock)
177  {
178  if (fTry)
179  TryEnter(pszName, pszFile, nLine);
180  else
181  Enter(pszName, pszFile, nLine);
182  }
183 
184  UniqueLock(Mutex* pmutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
185  {
186  if (!pmutexIn) return;
187 
188  *static_cast<Base*>(this) = Base(*pmutexIn, std::defer_lock);
189  if (fTry)
190  TryEnter(pszName, pszFile, nLine);
191  else
192  Enter(pszName, pszFile, nLine);
193  }
194 
196  {
197  if (Base::owns_lock())
198  LeaveCritical();
199  }
200 
201  operator bool()
202  {
203  return Base::owns_lock();
204  }
205 
206 protected:
207  // needed for reverse_lock
209 
210 public:
214  class reverse_lock {
215  public:
216  explicit reverse_lock(UniqueLock& _lock, const char* _guardname, const char* _file, int _line) : lock(_lock), file(_file), line(_line) {
217  CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line);
218  lock.unlock();
219  LeaveCritical();
220  lock.swap(templock);
221  }
222 
224  templock.swap(lock);
225  EnterCritical(lockname.c_str(), file.c_str(), line, lock.mutex());
226  lock.lock();
227  }
228 
229  private:
230  reverse_lock(reverse_lock const&);
231  reverse_lock& operator=(reverse_lock const&);
232 
235  std::string lockname;
236  const std::string file;
237  const int line;
238  };
239  friend class reverse_lock;
240 };
241 
242 #define REVERSE_LOCK(g) typename std::decay<decltype(g)>::type::reverse_lock UNIQUE_NAME(revlock)(g, #g, __FILE__, __LINE__)
243 
244 template<typename MutexArg>
246 
247 // When locking a Mutex, require negative capability to ensure the lock
248 // is not already held
251 
252 // When locking a GlobalMutex, just check it is not locked in the surrounding scope
255 
256 // When locking a RecursiveMutex, it's okay to already hold the lock
257 // but check that it is not known to be locked in the surrounding scope anyway
260 
261 #define LOCK(cs) DebugLock<decltype(cs)> UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
262 #define LOCK2(cs1, cs2) \
263  DebugLock<decltype(cs1)> criticalblock1(MaybeCheckNotHeld(cs1), #cs1, __FILE__, __LINE__); \
264  DebugLock<decltype(cs2)> criticalblock2(MaybeCheckNotHeld(cs2), #cs2, __FILE__, __LINE__)
265 #define TRY_LOCK(cs, name) DebugLock<decltype(cs)> name(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__, true)
266 #define WAIT_LOCK(cs, name) DebugLock<decltype(cs)> name(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
267 
268 #define ENTER_CRITICAL_SECTION(cs) \
269  { \
270  EnterCritical(#cs, __FILE__, __LINE__, &cs); \
271  (cs).lock(); \
272  }
273 
274 #define LEAVE_CRITICAL_SECTION(cs) \
275  { \
276  std::string lockname; \
277  CheckLastCritical((void*)(&cs), lockname, #cs, __FILE__, __LINE__); \
278  (cs).unlock(); \
279  LeaveCritical(); \
280  }
281 
305 #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
306 
308 {
309 private:
310  std::condition_variable condition;
311  std::mutex mutex;
312  int value;
313 
314 public:
315  explicit CSemaphore(int init) : value(init) {}
316 
317  void wait()
318  {
319  std::unique_lock<std::mutex> lock(mutex);
320  condition.wait(lock, [&]() { return value >= 1; });
321  value--;
322  }
323 
324  bool try_wait()
325  {
326  std::lock_guard<std::mutex> lock(mutex);
327  if (value < 1)
328  return false;
329  value--;
330  return true;
331  }
332 
333  void post()
334  {
335  {
336  std::lock_guard<std::mutex> lock(mutex);
337  value++;
338  }
339  condition.notify_one();
340  }
341 };
342 
345 {
346 private:
349 
350 public:
351  void Acquire()
352  {
353  if (fHaveGrant)
354  return;
355  sem->wait();
356  fHaveGrant = true;
357  }
358 
359  void Release()
360  {
361  if (!fHaveGrant)
362  return;
363  sem->post();
364  fHaveGrant = false;
365  }
366 
367  bool TryAcquire()
368  {
369  if (!fHaveGrant && sem->try_wait())
370  fHaveGrant = true;
371  return fHaveGrant;
372  }
373 
374  void MoveTo(CSemaphoreGrant& grant)
375  {
376  grant.Release();
377  grant.sem = sem;
378  grant.fHaveGrant = fHaveGrant;
379  fHaveGrant = false;
380  }
381 
382  CSemaphoreGrant() : sem(nullptr), fHaveGrant(false) {}
383 
384  explicit CSemaphoreGrant(CSemaphore& sema, bool fTry = false) : sem(&sema), fHaveGrant(false)
385  {
386  if (fTry)
387  TryAcquire();
388  else
389  Acquire();
390  }
391 
393  {
394  Release();
395  }
396 
397  operator bool() const
398  {
399  return fHaveGrant;
400  }
401 };
402 
403 #endif // BITCOIN_SYNC_H
void LeaveCritical()
Definition: sync.h:77
void MoveTo(CSemaphoreGrant &grant)
Definition: sync.h:374
void unlock() UNLOCK_FUNCTION()
Definition: sync.h:104
#define EXCLUSIVE_LOCK_FUNCTION(...)
Definition: threadsafety.h:42
reverse_lock(UniqueLock &_lock, const char *_guardname, const char *_file, int _line)
Definition: sync.h:216
void Enter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:155
UniqueLock & lock
Definition: sync.h:233
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
static void pool cs
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
RAII-style semaphore lock.
Definition: sync.h:344
bool try_wait()
Definition: sync.h:324
UniqueLock templock
Definition: sync.h:234
~AnnotatedMixin()
Definition: sync.h:95
void lock() EXCLUSIVE_LOCK_FUNCTION()
Definition: sync.h:99
void Acquire()
Definition: sync.h:351
bool LockStackEmpty()
Definition: sync.h:84
void AssertLockNotHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) LOCKS_EXCLUDED(cs)
Definition: sync.h:82
#define UNLOCK_FUNCTION(...)
Definition: threadsafety.h:46
CSemaphoreGrant(CSemaphore &sema, bool fTry=false)
Definition: sync.h:384
void CheckLastCritical(void *cs, std::string &lockname, const char *guardname, const char *file, int line)
Definition: sync.h:78
~CSemaphoreGrant()
Definition: sync.h:392
void DeleteLock(void *cs)
Definition: sync.h:83
bool try_lock() EXCLUSIVE_TRYLOCK_FUNCTION(true)
Definition: sync.h:109
void EnterCritical(const char *pszName, const char *pszFile, int nLine, MutexType *cs, bool fTry=false)
Definition: sync.h:76
#define LOCK(cs)
Definition: sync.h:261
const char * name
Definition: rest.cpp:46
UniqueLock(Mutex *pmutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
Definition: sync.h:184
CSemaphore * sem
Definition: sync.h:347
UniqueLock(Mutex &mutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(mutexIn)
Definition: sync.h:176
int value
Definition: sync.h:312
~UniqueLock() UNLOCK_FUNCTION()
Definition: sync.h:195
#define LOG_TIME_MICROS_WITH_CATEGORY(end_msg, log_category)
Definition: timer.h:99
void Release()
Definition: sync.h:359
void AssertLockHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: sync.h:80
CSemaphoreGrant()
Definition: sync.h:382
#define LOCKABLE
Definition: threadsafety.h:36
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::condition_variable condition
Definition: sync.h:310
Template mixin that adds -Wthread-safety locking annotations and lock order checking to a subset of t...
Definition: sync.h:92
const std::string file
Definition: sync.h:236
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
An RAII-style reverse lock.
Definition: sync.h:214
void wait()
Definition: sync.h:317
#define EXCLUSIVE_TRYLOCK_FUNCTION(...)
Definition: threadsafety.h:44
std::string lockname
Definition: sync.h:235
#define SCOPED_LOCKABLE
Definition: threadsafety.h:37
CSemaphore(int init)
Definition: sync.h:315
Mutex & MaybeCheckNotHeld(Mutex &cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) LOCK_RETURNED(cs)
Definition: sync.h:249
UniqueLock()
Definition: sync.h:208
Wrapper around std::unique_lock style lock for Mutex.
Definition: sync.h:152
void AssertLockNotHeldInline(const char *name, const char *file, int line, Mutex *cs) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: sync.h:145
bool TryEnter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:165
Different type to mark Mutex at global scope.
Definition: sync.h:141
void post()
Definition: sync.h:333
bool TryAcquire()
Definition: sync.h:367
bool fHaveGrant
Definition: sync.h:348
std::mutex mutex
Definition: sync.h:311