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