Bitcoin Core  21.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-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 template <typename MutexType>
52 void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false);
53 void LeaveCritical();
54 void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line);
55 std::string LocksHeld();
56 template <typename MutexType>
57 void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs);
58 template <typename MutexType>
59 void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs);
60 void DeleteLock(void* cs);
61 bool LockStackEmpty();
62 
68 extern bool g_debug_lockorder_abort;
69 #else
70 template <typename MutexType>
71 inline void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false) {}
72 inline void LeaveCritical() {}
73 inline void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) {}
74 template <typename MutexType>
75 inline void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs) {}
76 template <typename MutexType>
77 void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) LOCKS_EXCLUDED(cs) {}
78 inline void DeleteLock(void* cs) {}
79 inline bool LockStackEmpty() { return true; }
80 #endif
81 #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
82 #define AssertLockNotHeld(cs) AssertLockNotHeldInternal(#cs, __FILE__, __LINE__, &cs)
83 
88 template <typename PARENT>
89 class LOCKABLE AnnotatedMixin : public PARENT
90 {
91 public:
93  DeleteLock((void*)this);
94  }
95 
97  {
98  PARENT::lock();
99  }
100 
102  {
103  PARENT::unlock();
104  }
105 
107  {
108  return PARENT::try_lock();
109  }
110 
111  using UniqueLock = std::unique_lock<PARENT>;
112 #ifdef __clang__
113  const AnnotatedMixin& operator!() const { return *this; }
117 #endif // __clang__
118 };
119 
125 
128 
129 #ifdef DEBUG_LOCKCONTENTION
130 void PrintLockContention(const char* pszName, const char* pszFile, int nLine);
131 #endif
132 
134 template <typename Mutex, typename Base = typename Mutex::UniqueLock>
135 class SCOPED_LOCKABLE UniqueLock : public Base
136 {
137 private:
138  void Enter(const char* pszName, const char* pszFile, int nLine)
139  {
140  EnterCritical(pszName, pszFile, nLine, Base::mutex());
141 #ifdef DEBUG_LOCKCONTENTION
142  if (!Base::try_lock()) {
143  PrintLockContention(pszName, pszFile, nLine);
144 #endif
145  Base::lock();
146 #ifdef DEBUG_LOCKCONTENTION
147  }
148 #endif
149  }
150 
151  bool TryEnter(const char* pszName, const char* pszFile, int nLine)
152  {
153  EnterCritical(pszName, pszFile, nLine, Base::mutex(), true);
154  Base::try_lock();
155  if (!Base::owns_lock())
156  LeaveCritical();
157  return Base::owns_lock();
158  }
159 
160 public:
161  UniqueLock(Mutex& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(mutexIn) : Base(mutexIn, std::defer_lock)
162  {
163  if (fTry)
164  TryEnter(pszName, pszFile, nLine);
165  else
166  Enter(pszName, pszFile, nLine);
167  }
168 
169  UniqueLock(Mutex* pmutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
170  {
171  if (!pmutexIn) return;
172 
173  *static_cast<Base*>(this) = Base(*pmutexIn, std::defer_lock);
174  if (fTry)
175  TryEnter(pszName, pszFile, nLine);
176  else
177  Enter(pszName, pszFile, nLine);
178  }
179 
181  {
182  if (Base::owns_lock())
183  LeaveCritical();
184  }
185 
186  operator bool()
187  {
188  return Base::owns_lock();
189  }
190 
191 protected:
192  // needed for reverse_lock
194 
195 public:
199  class reverse_lock {
200  public:
201  explicit reverse_lock(UniqueLock& _lock, const char* _guardname, const char* _file, int _line) : lock(_lock), file(_file), line(_line) {
202  CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line);
203  lock.unlock();
204  LeaveCritical();
205  lock.swap(templock);
206  }
207 
209  templock.swap(lock);
210  EnterCritical(lockname.c_str(), file.c_str(), line, lock.mutex());
211  lock.lock();
212  }
213 
214  private:
215  reverse_lock(reverse_lock const&);
216  reverse_lock& operator=(reverse_lock const&);
217 
220  std::string lockname;
221  const std::string file;
222  const int line;
223  };
224  friend class reverse_lock;
225 };
226 
227 #define REVERSE_LOCK(g) typename std::decay<decltype(g)>::type::reverse_lock PASTE2(revlock, __COUNTER__)(g, #g, __FILE__, __LINE__)
228 
229 template<typename MutexArg>
231 
232 #define LOCK(cs) DebugLock<decltype(cs)> PASTE2(criticalblock, __COUNTER__)(cs, #cs, __FILE__, __LINE__)
233 #define LOCK2(cs1, cs2) \
234  DebugLock<decltype(cs1)> criticalblock1(cs1, #cs1, __FILE__, __LINE__); \
235  DebugLock<decltype(cs2)> criticalblock2(cs2, #cs2, __FILE__, __LINE__);
236 #define TRY_LOCK(cs, name) DebugLock<decltype(cs)> name(cs, #cs, __FILE__, __LINE__, true)
237 #define WAIT_LOCK(cs, name) DebugLock<decltype(cs)> name(cs, #cs, __FILE__, __LINE__)
238 
239 #define ENTER_CRITICAL_SECTION(cs) \
240  { \
241  EnterCritical(#cs, __FILE__, __LINE__, &cs); \
242  (cs).lock(); \
243  }
244 
245 #define LEAVE_CRITICAL_SECTION(cs) \
246  { \
247  std::string lockname; \
248  CheckLastCritical((void*)(&cs), lockname, #cs, __FILE__, __LINE__); \
249  (cs).unlock(); \
250  LeaveCritical(); \
251  }
252 
276 #define WITH_LOCK(cs, code) [&]() -> decltype(auto) { LOCK(cs); code; }()
277 
279 {
280 private:
281  std::condition_variable condition;
282  std::mutex mutex;
283  int value;
284 
285 public:
286  explicit CSemaphore(int init) : value(init) {}
287 
288  void wait()
289  {
290  std::unique_lock<std::mutex> lock(mutex);
291  condition.wait(lock, [&]() { return value >= 1; });
292  value--;
293  }
294 
295  bool try_wait()
296  {
297  std::lock_guard<std::mutex> lock(mutex);
298  if (value < 1)
299  return false;
300  value--;
301  return true;
302  }
303 
304  void post()
305  {
306  {
307  std::lock_guard<std::mutex> lock(mutex);
308  value++;
309  }
310  condition.notify_one();
311  }
312 };
313 
316 {
317 private:
320 
321 public:
322  void Acquire()
323  {
324  if (fHaveGrant)
325  return;
326  sem->wait();
327  fHaveGrant = true;
328  }
329 
330  void Release()
331  {
332  if (!fHaveGrant)
333  return;
334  sem->post();
335  fHaveGrant = false;
336  }
337 
338  bool TryAcquire()
339  {
340  if (!fHaveGrant && sem->try_wait())
341  fHaveGrant = true;
342  return fHaveGrant;
343  }
344 
345  void MoveTo(CSemaphoreGrant& grant)
346  {
347  grant.Release();
348  grant.sem = sem;
349  grant.fHaveGrant = fHaveGrant;
350  fHaveGrant = false;
351  }
352 
353  CSemaphoreGrant() : sem(nullptr), fHaveGrant(false) {}
354 
355  explicit CSemaphoreGrant(CSemaphore& sema, bool fTry = false) : sem(&sema), fHaveGrant(false)
356  {
357  if (fTry)
358  TryAcquire();
359  else
360  Acquire();
361  }
362 
364  {
365  Release();
366  }
367 
368  operator bool() const
369  {
370  return fHaveGrant;
371  }
372 };
373 
374 #endif // BITCOIN_SYNC_H
CSemaphore::post
void post()
Definition: sync.h:304
UniqueLock::reverse_lock::~reverse_lock
~reverse_lock()
Definition: sync.h:208
UniqueLock::Enter
void Enter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:138
EXCLUSIVE_LOCK_FUNCTION
#define EXCLUSIVE_LOCK_FUNCTION(...)
Definition: threadsafety.h:42
UNLOCK_FUNCTION
#define UNLOCK_FUNCTION(...)
Definition: threadsafety.h:46
UniqueLock::reverse_lock::reverse_lock
reverse_lock(UniqueLock &_lock, const char *_guardname, const char *_file, int _line)
Definition: sync.h:201
CSemaphoreGrant::fHaveGrant
bool fHaveGrant
Definition: sync.h:319
UniqueLock::reverse_lock::line
const int line
Definition: sync.h:222
UniqueLock::reverse_lock::lock
UniqueLock & lock
Definition: sync.h:218
CSemaphoreGrant::MoveTo
void MoveTo(CSemaphoreGrant &grant)
Definition: sync.h:345
UniqueLock::~UniqueLock
~UniqueLock() UNLOCK_FUNCTION()
Definition: sync.h:180
AnnotatedMixin
Template mixin that adds -Wthread-safety locking annotations and lock order checking to a subset of t...
Definition: sync.h:89
CheckLastCritical
void CheckLastCritical(void *cs, std::string &lockname, const char *guardname, const char *file, int line)
Definition: sync.h:73
CSemaphoreGrant::~CSemaphoreGrant
~CSemaphoreGrant()
Definition: sync.h:363
macros.h
DeleteLock
void DeleteLock(void *cs)
Definition: sync.h:78
CSemaphore::condition
std::condition_variable condition
Definition: sync.h:281
UniqueLock::UniqueLock
UniqueLock()
Definition: sync.h:193
UniqueLock::reverse_lock::templock
UniqueLock templock
Definition: sync.h:219
LeaveCritical
void LeaveCritical()
Definition: sync.h:72
CSemaphore::CSemaphore
CSemaphore(int init)
Definition: sync.h:286
SCOPED_LOCKABLE
#define SCOPED_LOCKABLE
Definition: threadsafety.h:37
CSemaphore
Definition: sync.h:278
CSemaphoreGrant
RAII-style semaphore lock.
Definition: sync.h:315
AnnotatedMixin::unlock
void unlock() UNLOCK_FUNCTION()
Definition: sync.h:101
threadsafety.h
CSemaphore::mutex
std::mutex mutex
Definition: sync.h:282
CSemaphoreGrant::CSemaphoreGrant
CSemaphoreGrant()
Definition: sync.h:353
LOCKABLE
#define LOCKABLE
Definition: threadsafety.h:36
AssertLockHeldInternal
void AssertLockHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: sync.h:75
CSemaphoreGrant::TryAcquire
bool TryAcquire()
Definition: sync.h:338
EXCLUSIVE_TRYLOCK_FUNCTION
#define EXCLUSIVE_TRYLOCK_FUNCTION(...)
Definition: threadsafety.h:44
cs
static void pool cs
Definition: mempool_eviction.cpp:12
Mutex
AnnotatedMixin< std::mutex > Mutex
Wrapped mutex: supports waiting but not recursive locking.
Definition: sync.h:127
LockStackEmpty
bool LockStackEmpty()
Definition: sync.h:79
UniqueLock::TryEnter
bool TryEnter(const char *pszName, const char *pszFile, int nLine)
Definition: sync.h:151
UniqueLock::reverse_lock::file
const std::string file
Definition: sync.h:221
UniqueLock
Wrapper around std::unique_lock style lock for Mutex.
Definition: sync.h:135
LOCKS_EXCLUDED
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
EnterCritical
void EnterCritical(const char *pszName, const char *pszFile, int nLine, MutexType *cs, bool fTry=false)
Definition: sync.h:71
AnnotatedMixin::~AnnotatedMixin
~AnnotatedMixin()
Definition: sync.h:92
EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
CSemaphoreGrant::Acquire
void Acquire()
Definition: sync.h:322
UniqueLock::UniqueLock
UniqueLock(Mutex *pmutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn)
Definition: sync.h:169
CSemaphore::try_wait
bool try_wait()
Definition: sync.h:295
CSemaphoreGrant::Release
void Release()
Definition: sync.h:330
AnnotatedMixin::lock
void lock() EXCLUSIVE_LOCK_FUNCTION()
Definition: sync.h:96
UniqueLock::reverse_lock::lockname
std::string lockname
Definition: sync.h:220
CSemaphoreGrant::CSemaphoreGrant
CSemaphoreGrant(CSemaphore &sema, bool fTry=false)
Definition: sync.h:355
AnnotatedMixin::try_lock
bool try_lock() EXCLUSIVE_TRYLOCK_FUNCTION(true)
Definition: sync.h:106
AssertLockNotHeldInternal
void AssertLockNotHeldInternal(const char *pszName, const char *pszFile, int nLine, MutexType *cs) LOCKS_EXCLUDED(cs)
Definition: sync.h:77
CSemaphore::wait
void wait()
Definition: sync.h:288
CSemaphoreGrant::sem
CSemaphore * sem
Definition: sync.h:318
UniqueLock::UniqueLock
UniqueLock(Mutex &mutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(mutexIn)
Definition: sync.h:161
CSemaphore::value
int value
Definition: sync.h:283
UniqueLock::reverse_lock
An RAII-style reverse lock.
Definition: sync.h:199