Bitcoin Core  0.20.99
P2P Digital Currency
sync.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 #include <threadsafety.h>
10 #include <util/macros.h>
11 
12 #include <condition_variable>
13 #include <mutex>
14 #include <string>
15 #include <thread>
16 
18 // //
19 // THE SIMPLE DEFINITION, EXCLUDING DEBUG CODE //
20 // //
22 
23 /*
24 RecursiveMutex mutex;
25  std::recursive_mutex mutex;
26 
27 LOCK(mutex);
28  std::unique_lock<std::recursive_mutex> criticalblock(mutex);
29 
30 LOCK2(mutex1, mutex2);
31  std::unique_lock<std::recursive_mutex> criticalblock1(mutex1);
32  std::unique_lock<std::recursive_mutex> criticalblock2(mutex2);
33 
34 TRY_LOCK(mutex, name);
35  std::unique_lock<std::recursive_mutex> name(mutex, std::try_to_lock_t);
36 
37 ENTER_CRITICAL_SECTION(mutex); // no RAII
38  mutex.lock();
39 
40 LEAVE_CRITICAL_SECTION(mutex); // no RAII
41  mutex.unlock();
42  */
43 
45 // //
46 // THE ACTUAL IMPLEMENTATION //
47 // //
49 
50 #ifdef DEBUG_LOCKORDER
51 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false);
52 void LeaveCritical();
53 void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line);
54 std::string LocksHeld();
55 template <typename MutexType>
56 void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) ASSERT_EXCLUSIVE_LOCK(cs);
57 void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs);
58 void DeleteLock(void* cs);
59 bool LockStackEmpty();
60 
66 extern bool g_debug_lockorder_abort;
67 #else
68 inline void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false) {}
69 inline void LeaveCritical() {}
70 inline void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) {}
71 template <typename MutexType>
72 inline void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) ASSERT_EXCLUSIVE_LOCK(cs) {}
73 inline void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) {}
74 inline void DeleteLock(void* cs) {}
75 inline bool LockStackEmpty() { return true; }
76 #endif
77 #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
78 #define AssertLockNotHeld(cs) AssertLockNotHeldInternal(#cs, __FILE__, __LINE__, &cs)
79 
84 template <typename PARENT>
85 class LOCKABLE AnnotatedMixin : public PARENT
86 {
87 public:
89  DeleteLock((void*)this);
90  }
91 
93  {
94  PARENT::lock();
95  }
96 
98  {
99  PARENT::unlock();
100  }
101 
103  {
104  return PARENT::try_lock();
105  }
106 
107  using UniqueLock = std::unique_lock<PARENT>;
108 #ifdef __clang__
109  const AnnotatedMixin& operator!() const { return *this; }
113 #endif // __clang__
114 };
115 
121 
124 
125 #ifdef DEBUG_LOCKCONTENTION
126 void PrintLockContention(const char* pszName, const char* pszFile, int nLine);
127 #endif
128 
130 template <typename Mutex, typename Base = typename Mutex::UniqueLock>
131 class SCOPED_LOCKABLE UniqueLock : public Base
132 {
133 private:
134  void Enter(const char* pszName, const char* pszFile, int nLine)
135  {
136  EnterCritical(pszName, pszFile, nLine, (void*)(Base::mutex()));
137 #ifdef DEBUG_LOCKCONTENTION
138  if (!Base::try_lock()) {
139  PrintLockContention(pszName, pszFile, nLine);
140 #endif
141  Base::lock();
142 #ifdef DEBUG_LOCKCONTENTION
143  }
144 #endif
145  }
146 
147  bool TryEnter(const char* pszName, const char* pszFile, int nLine)
148  {
149  EnterCritical(pszName, pszFile, nLine, (void*)(Base::mutex()), true);
150  Base::try_lock();
151  if (!Base::owns_lock())
152  LeaveCritical();
153  return Base::owns_lock();
154  }
155 
156 public:
157  UniqueLock(Mutex& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(mutexIn) : Base(mutexIn, std::defer_lock)
158  {
159  if (fTry)
160  TryEnter(pszName, pszFile, nLine);
161  else
162  Enter(pszName, pszFile, nLine);
163  }
164 
165  UniqueLock(Mutex* pmutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
166  {
167  if (!pmutexIn) return;
168 
169  *static_cast<Base*>(this) = Base(*pmutexIn, std::defer_lock);
170  if (fTry)
171  TryEnter(pszName, pszFile, nLine);
172  else
173  Enter(pszName, pszFile, nLine);
174  }
175 
177  {
178  if (Base::owns_lock())
179  LeaveCritical();
180  }
181 
182  operator bool()
183  {
184  return Base::owns_lock();
185  }
186 
187 protected:
188  // needed for reverse_lock
190 
191 public:
195  class reverse_lock {
196  public:
197  explicit reverse_lock(UniqueLock& _lock, const char* _guardname, const char* _file, int _line) : lock(_lock), file(_file), line(_line) {
198  CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line);
199  lock.unlock();
200  LeaveCritical();
201  lock.swap(templock);
202  }
203 
205  templock.swap(lock);
206  EnterCritical(lockname.c_str(), file.c_str(), line, (void*)lock.mutex());
207  lock.lock();
208  }
209 
210  private:
211  reverse_lock(reverse_lock const&);
212  reverse_lock& operator=(reverse_lock const&);
213 
216  std::string lockname;
217  const std::string file;
218  const int line;
219  };
220  friend class reverse_lock;
221 };
222 
223 #define REVERSE_LOCK(g) typename std::decay<decltype(g)>::type::reverse_lock PASTE2(revlock, __COUNTER__)(g, #g, __FILE__, __LINE__)
224 
225 template<typename MutexArg>
227 
228 #define LOCK(cs) DebugLock<decltype(cs)> PASTE2(criticalblock, __COUNTER__)(cs, #cs, __FILE__, __LINE__)
229 #define LOCK2(cs1, cs2) \
230  DebugLock<decltype(cs1)> criticalblock1(cs1, #cs1, __FILE__, __LINE__); \
231  DebugLock<decltype(cs2)> criticalblock2(cs2, #cs2, __FILE__, __LINE__);
232 #define TRY_LOCK(cs, name) DebugLock<decltype(cs)> name(cs, #cs, __FILE__, __LINE__, true)
233 #define WAIT_LOCK(cs, name) DebugLock<decltype(cs)> name(cs, #cs, __FILE__, __LINE__)
234 
235 #define ENTER_CRITICAL_SECTION(cs) \
236  { \
237  EnterCritical(#cs, __FILE__, __LINE__, (void*)(&cs)); \
238  (cs).lock(); \
239  }
240 
241 #define LEAVE_CRITICAL_SECTION(cs) \
242  { \
243  (cs).unlock(); \
244  LeaveCritical(); \
245  }
246 
255 #define WITH_LOCK(cs, code) [&] { LOCK(cs); code; }()
256 
258 {
259 private:
260  std::condition_variable condition;
261  std::mutex mutex;
262  int value;
263 
264 public:
265  explicit CSemaphore(int init) : value(init) {}
266 
267  void wait()
268  {
269  std::unique_lock<std::mutex> lock(mutex);
270  condition.wait(lock, [&]() { return value >= 1; });
271  value--;
272  }
273 
274  bool try_wait()
275  {
276  std::lock_guard<std::mutex> lock(mutex);
277  if (value < 1)
278  return false;
279  value--;
280  return true;
281  }
282 
283  void post()
284  {
285  {
286  std::lock_guard<std::mutex> lock(mutex);
287  value++;
288  }
289  condition.notify_one();
290  }
291 };
292 
295 {
296 private:
299 
300 public:
301  void Acquire()
302  {
303  if (fHaveGrant)
304  return;
305  sem->wait();
306  fHaveGrant = true;
307  }
308 
309  void Release()
310  {
311  if (!fHaveGrant)
312  return;
313  sem->post();
314  fHaveGrant = false;
315  }
316 
317  bool TryAcquire()
318  {
319  if (!fHaveGrant && sem->try_wait())
320  fHaveGrant = true;
321  return fHaveGrant;
322  }
323 
324  void MoveTo(CSemaphoreGrant& grant)
325  {
326  grant.Release();
327  grant.sem = sem;
328  grant.fHaveGrant = fHaveGrant;
329  fHaveGrant = false;
330  }
331 
332  CSemaphoreGrant() : sem(nullptr), fHaveGrant(false) {}
333 
334  explicit CSemaphoreGrant(CSemaphore& sema, bool fTry = false) : sem(&sema), fHaveGrant(false)
335  {
336  if (fTry)
337  TryAcquire();
338  else
339  Acquire();
340  }
341 
343  {
344  Release();
345  }
346 
347  operator bool() const
348  {
349  return fHaveGrant;
350  }
351 };
352 
353 // Utility class for indicating to compiler thread analysis that a mutex is
354 // locked (when it couldn't be determined otherwise).
356 {
357  template <typename Mutex>
359  {
360 #ifdef DEBUG_LOCKORDER
361  AssertLockHeld(mutex);
362 #endif
363  }
365 };
366 
367 #endif // BITCOIN_SYNC_H
void LeaveCritical()
Definition: sync.h:69
void MoveTo(CSemaphoreGrant &grant)
Definition: sync.h:324
void unlock() UNLOCK_FUNCTION()
Definition: sync.h:97
#define EXCLUSIVE_LOCK_FUNCTION(...)
Definition: threadsafety.h:46
reverse_lock(UniqueLock &_lock, const char *_guardname, const char *_file, int _line)
Definition: sync.h:197
void AssertLockNotHeldInternal(const char *pszName, const char *pszFile, int nLine, void *cs)
Definition: sync.h:73
void Enter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:134
UniqueLock & lock
Definition: sync.h:214
static void pool cs
RAII-style semaphore lock.
Definition: sync.h:294
bool try_wait()
Definition: sync.h:274
UniqueLock templock
Definition: sync.h:215
~AnnotatedMixin()
Definition: sync.h:88
void lock() EXCLUSIVE_LOCK_FUNCTION()
Definition: sync.h:92
void Acquire()
Definition: sync.h:301
void AssertLockHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) ASSERT_EXCLUSIVE_LOCK(cs)
Definition: sync.h:72
bool LockStackEmpty()
Definition: sync.h:75
#define UNLOCK_FUNCTION(...)
Definition: threadsafety.h:50
CSemaphoreGrant(CSemaphore &sema, bool fTry=false)
Definition: sync.h:334
void CheckLastCritical(void *cs, std::string &lockname, const char *guardname, const char *file, int line)
Definition: sync.h:70
#define AssertLockHeld(cs)
Definition: sync.h:77
~CSemaphoreGrant()
Definition: sync.h:342
void DeleteLock(void *cs)
Definition: sync.h:74
bool try_lock() EXCLUSIVE_TRYLOCK_FUNCTION(true)
Definition: sync.h:102
UniqueLock(Mutex *pmutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
Definition: sync.h:165
CSemaphore * sem
Definition: sync.h:297
UniqueLock(Mutex &mutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(mutexIn)
Definition: sync.h:157
int value
Definition: sync.h:262
~UniqueLock() UNLOCK_FUNCTION()
Definition: sync.h:176
void Release()
Definition: sync.h:309
CSemaphoreGrant()
Definition: sync.h:332
void EnterCritical(const char *pszName, const char *pszFile, int nLine, void *cs, bool fTry=false)
Definition: sync.h:68
#define LOCKABLE
Definition: threadsafety.h:38
std::condition_variable condition
Definition: sync.h:260
Template mixin that adds -Wthread-safety locking annotations and lock order checking to a subset of t...
Definition: sync.h:85
const std::string file
Definition: sync.h:217
~LockAssertion() UNLOCK_FUNCTION()
Definition: sync.h:364
An RAII-style reverse lock.
Definition: sync.h:195
void wait()
Definition: sync.h:267
#define EXCLUSIVE_TRYLOCK_FUNCTION(...)
Definition: threadsafety.h:48
std::string lockname
Definition: sync.h:216
#define SCOPED_LOCKABLE
Definition: threadsafety.h:39
CSemaphore(int init)
Definition: sync.h:265
UniqueLock()
Definition: sync.h:189
LockAssertion(Mutex &mutex) EXCLUSIVE_LOCK_FUNCTION(mutex)
Definition: sync.h:358
Wrapper around std::unique_lock style lock for Mutex.
Definition: sync.h:131
AnnotatedMixin< std::mutex > Mutex
Wrapped mutex: supports waiting but not recursive locking.
Definition: sync.h:123
bool TryEnter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:147
void post()
Definition: sync.h:283
bool TryAcquire()
Definition: sync.h:317
bool fHaveGrant
Definition: sync.h:298
#define ASSERT_EXCLUSIVE_LOCK(...)
Definition: threadsafety.h:56
std::mutex mutex
Definition: sync.h:261