You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

mutex.h 49 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // mutex.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file defines a `Mutex` -- a mutually exclusive lock -- and the
  20. // most common type of synchronization primitive for facilitating locks on
  21. // shared resources. A mutex is used to prevent multiple threads from accessing
  22. // and/or writing to a shared resource concurrently.
  23. //
  24. // Unlike a `std::mutex`, the Abseil `Mutex` provides the following additional
  25. // features:
  26. // * Conditional predicates intrinsic to the `Mutex` object
  27. // * Shared/reader locks, in addition to standard exclusive/writer locks
  28. // * Deadlock detection and debug support.
  29. //
  30. // The following helper classes are also defined within this file:
  31. //
  32. // MutexLock - An RAII wrapper to acquire and release a `Mutex` for exclusive/
  33. // write access within the current scope.
  34. //
  35. // ReaderMutexLock
  36. // - An RAII wrapper to acquire and release a `Mutex` for shared/read
  37. // access within the current scope.
  38. //
  39. // WriterMutexLock
  40. // - Effectively an alias for `MutexLock` above, designed for use in
  41. // distinguishing reader and writer locks within code.
  42. //
  43. // In addition to simple mutex locks, this file also defines ways to perform
  44. // locking under certain conditions.
  45. //
  46. // Condition - (Preferred) Used to wait for a particular predicate that
  47. // depends on state protected by the `Mutex` to become true.
  48. // CondVar - A lower-level variant of `Condition` that relies on
  49. // application code to explicitly signal the `CondVar` when
  50. // a condition has been met.
  51. //
  52. // See below for more information on using `Condition` or `CondVar`.
  53. //
  54. // Mutexes and mutex behavior can be quite complicated. The information within
  55. // this header file is limited, as a result. Please consult the Mutex guide for
  56. // more complete information and examples.
  57. #ifndef ABSL_SYNCHRONIZATION_MUTEX_H_
  58. #define ABSL_SYNCHRONIZATION_MUTEX_H_
  59. #include <atomic>
  60. #include <cstdint>
  61. #include <string>
  62. #include "absl/base/const_init.h"
  63. #include "absl/base/internal/identity.h"
  64. #include "absl/base/internal/low_level_alloc.h"
  65. #include "absl/base/internal/thread_identity.h"
  66. #include "absl/base/internal/tsan_mutex_interface.h"
  67. #include "absl/base/port.h"
  68. #include "absl/base/thread_annotations.h"
  69. #include "absl/synchronization/internal/kernel_timeout.h"
  70. #include "absl/synchronization/internal/per_thread_sem.h"
  71. #include "absl/time/time.h"
  72. namespace absl
  73. {
  74. ABSL_NAMESPACE_BEGIN
  75. class Condition;
  76. struct SynchWaitParams;
  77. // -----------------------------------------------------------------------------
  78. // Mutex
  79. // -----------------------------------------------------------------------------
  80. //
  81. // A `Mutex` is a non-reentrant (aka non-recursive) Mutually Exclusive lock
  82. // on some resource, typically a variable or data structure with associated
  83. // invariants. Proper usage of mutexes prevents concurrent access by different
  84. // threads to the same resource.
  85. //
  86. // A `Mutex` has two basic operations: `Mutex::Lock()` and `Mutex::Unlock()`.
  87. // The `Lock()` operation *acquires* a `Mutex` (in a state known as an
  88. // *exclusive* -- or write -- lock), while the `Unlock()` operation *releases* a
  89. // Mutex. During the span of time between the Lock() and Unlock() operations,
  90. // a mutex is said to be *held*. By design all mutexes support exclusive/write
  91. // locks, as this is the most common way to use a mutex.
  92. //
  93. // The `Mutex` state machine for basic lock/unlock operations is quite simple:
  94. //
  95. // | | Lock() | Unlock() |
  96. // |----------------+------------+----------|
  97. // | Free | Exclusive | invalid |
  98. // | Exclusive | blocks | Free |
  99. //
  100. // Attempts to `Unlock()` must originate from the thread that performed the
  101. // corresponding `Lock()` operation.
  102. //
  103. // An "invalid" operation is disallowed by the API. The `Mutex` implementation
  104. // is allowed to do anything on an invalid call, including but not limited to
  105. // crashing with a useful error message, silently succeeding, or corrupting
  106. // data structures. In debug mode, the implementation attempts to crash with a
  107. // useful error message.
  108. //
  109. // `Mutex` is not guaranteed to be "fair" in prioritizing waiting threads; it
  110. // is, however, approximately fair over long periods, and starvation-free for
  111. // threads at the same priority.
  112. //
  113. // The lock/unlock primitives are now annotated with lock annotations
  114. // defined in (base/thread_annotations.h). When writing multi-threaded code,
  115. // you should use lock annotations whenever possible to document your lock
  116. // synchronization policy. Besides acting as documentation, these annotations
  117. // also help compilers or static analysis tools to identify and warn about
  118. // issues that could potentially result in race conditions and deadlocks.
  119. //
  120. // For more information about the lock annotations, please see
  121. // [Thread Safety Analysis](http://clang.llvm.org/docs/ThreadSafetyAnalysis.html)
  122. // in the Clang documentation.
  123. //
  124. // See also `MutexLock`, below, for scoped `Mutex` acquisition.
  125. class ABSL_LOCKABLE Mutex
  126. {
  127. public:
  128. // Creates a `Mutex` that is not held by anyone. This constructor is
  129. // typically used for Mutexes allocated on the heap or the stack.
  130. //
  131. // To create `Mutex` instances with static storage duration
  132. // (e.g. a namespace-scoped or global variable), see
  133. // `Mutex::Mutex(absl::kConstInit)` below instead.
  134. Mutex();
  135. // Creates a mutex with static storage duration. A global variable
  136. // constructed this way avoids the lifetime issues that can occur on program
  137. // startup and shutdown. (See absl/base/const_init.h.)
  138. //
  139. // For Mutexes allocated on the heap and stack, instead use the default
  140. // constructor, which can interact more fully with the thread sanitizer.
  141. //
  142. // Example usage:
  143. // namespace foo {
  144. // ABSL_CONST_INIT absl::Mutex mu(absl::kConstInit);
  145. // }
  146. explicit constexpr Mutex(absl::ConstInitType);
  147. ~Mutex();
  148. // Mutex::Lock()
  149. //
  150. // Blocks the calling thread, if necessary, until this `Mutex` is free, and
  151. // then acquires it exclusively. (This lock is also known as a "write lock.")
  152. void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION();
  153. // Mutex::Unlock()
  154. //
  155. // Releases this `Mutex` and returns it from the exclusive/write state to the
  156. // free state. Calling thread must hold the `Mutex` exclusively.
  157. void Unlock() ABSL_UNLOCK_FUNCTION();
  158. // Mutex::TryLock()
  159. //
  160. // If the mutex can be acquired without blocking, does so exclusively and
  161. // returns `true`. Otherwise, returns `false`. Returns `true` with high
  162. // probability if the `Mutex` was free.
  163. bool TryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true);
  164. // Mutex::AssertHeld()
  165. //
  166. // Require that the mutex be held exclusively (write mode) by this thread.
  167. //
  168. // If the mutex is not currently held by this thread, this function may report
  169. // an error (typically by crashing with a diagnostic) or it may do nothing.
  170. // This function is intended only as a tool to assist debugging; it doesn't
  171. // guarantee correctness.
  172. void AssertHeld() const ABSL_ASSERT_EXCLUSIVE_LOCK();
  173. // ---------------------------------------------------------------------------
  174. // Reader-Writer Locking
  175. // ---------------------------------------------------------------------------
  176. // A Mutex can also be used as a starvation-free reader-writer lock.
  177. // Neither read-locks nor write-locks are reentrant/recursive to avoid
  178. // potential client programming errors.
  179. //
  180. // The Mutex API provides `Writer*()` aliases for the existing `Lock()`,
  181. // `Unlock()` and `TryLock()` methods for use within applications mixing
  182. // reader/writer locks. Using `Reader*()` and `Writer*()` operations in this
  183. // manner can make locking behavior clearer when mixing read and write modes.
  184. //
  185. // Introducing reader locks necessarily complicates the `Mutex` state
  186. // machine somewhat. The table below illustrates the allowed state transitions
  187. // of a mutex in such cases. Note that ReaderLock() may block even if the lock
  188. // is held in shared mode; this occurs when another thread is blocked on a
  189. // call to WriterLock().
  190. //
  191. // ---------------------------------------------------------------------------
  192. // Operation: WriterLock() Unlock() ReaderLock() ReaderUnlock()
  193. // ---------------------------------------------------------------------------
  194. // State
  195. // ---------------------------------------------------------------------------
  196. // Free Exclusive invalid Shared(1) invalid
  197. // Shared(1) blocks invalid Shared(2) or blocks Free
  198. // Shared(n) n>1 blocks invalid Shared(n+1) or blocks Shared(n-1)
  199. // Exclusive blocks Free blocks invalid
  200. // ---------------------------------------------------------------------------
  201. //
  202. // In comments below, "shared" refers to a state of Shared(n) for any n > 0.
  203. // Mutex::ReaderLock()
  204. //
  205. // Blocks the calling thread, if necessary, until this `Mutex` is either free,
  206. // or in shared mode, and then acquires a share of it. Note that
  207. // `ReaderLock()` will block if some other thread has an exclusive/writer lock
  208. // on the mutex.
  209. void ReaderLock() ABSL_SHARED_LOCK_FUNCTION();
  210. // Mutex::ReaderUnlock()
  211. //
  212. // Releases a read share of this `Mutex`. `ReaderUnlock` may return a mutex to
  213. // the free state if this thread holds the last reader lock on the mutex. Note
  214. // that you cannot call `ReaderUnlock()` on a mutex held in write mode.
  215. void ReaderUnlock() ABSL_UNLOCK_FUNCTION();
  216. // Mutex::ReaderTryLock()
  217. //
  218. // If the mutex can be acquired without blocking, acquires this mutex for
  219. // shared access and returns `true`. Otherwise, returns `false`. Returns
  220. // `true` with high probability if the `Mutex` was free or shared.
  221. bool ReaderTryLock() ABSL_SHARED_TRYLOCK_FUNCTION(true);
  222. // Mutex::AssertReaderHeld()
  223. //
  224. // Require that the mutex be held at least in shared mode (read mode) by this
  225. // thread.
  226. //
  227. // If the mutex is not currently held by this thread, this function may report
  228. // an error (typically by crashing with a diagnostic) or it may do nothing.
  229. // This function is intended only as a tool to assist debugging; it doesn't
  230. // guarantee correctness.
  231. void AssertReaderHeld() const ABSL_ASSERT_SHARED_LOCK();
  232. // Mutex::WriterLock()
  233. // Mutex::WriterUnlock()
  234. // Mutex::WriterTryLock()
  235. //
  236. // Aliases for `Mutex::Lock()`, `Mutex::Unlock()`, and `Mutex::TryLock()`.
  237. //
  238. // These methods may be used (along with the complementary `Reader*()`
  239. // methods) to distingish simple exclusive `Mutex` usage (`Lock()`,
  240. // etc.) from reader/writer lock usage.
  241. void WriterLock() ABSL_EXCLUSIVE_LOCK_FUNCTION()
  242. {
  243. this->Lock();
  244. }
  245. void WriterUnlock() ABSL_UNLOCK_FUNCTION()
  246. {
  247. this->Unlock();
  248. }
  249. bool WriterTryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true)
  250. {
  251. return this->TryLock();
  252. }
  253. // ---------------------------------------------------------------------------
  254. // Conditional Critical Regions
  255. // ---------------------------------------------------------------------------
  256. // Conditional usage of a `Mutex` can occur using two distinct paradigms:
  257. //
  258. // * Use of `Mutex` member functions with `Condition` objects.
  259. // * Use of the separate `CondVar` abstraction.
  260. //
  261. // In general, prefer use of `Condition` and the `Mutex` member functions
  262. // listed below over `CondVar`. When there are multiple threads waiting on
  263. // distinctly different conditions, however, a battery of `CondVar`s may be
  264. // more efficient. This section discusses use of `Condition` objects.
  265. //
  266. // `Mutex` contains member functions for performing lock operations only under
  267. // certain conditions, of class `Condition`. For correctness, the `Condition`
  268. // must return a boolean that is a pure function, only of state protected by
  269. // the `Mutex`. The condition must be invariant w.r.t. environmental state
  270. // such as thread, cpu id, or time, and must be `noexcept`. The condition will
  271. // always be invoked with the mutex held in at least read mode, so you should
  272. // not block it for long periods or sleep it on a timer.
  273. //
  274. // Since a condition must not depend directly on the current time, use
  275. // `*WithTimeout()` member function variants to make your condition
  276. // effectively true after a given duration, or `*WithDeadline()` variants to
  277. // make your condition effectively true after a given time.
  278. //
  279. // The condition function should have no side-effects aside from debug
  280. // logging; as a special exception, the function may acquire other mutexes
  281. // provided it releases all those that it acquires. (This exception was
  282. // required to allow logging.)
  283. // Mutex::Await()
  284. //
  285. // Unlocks this `Mutex` and blocks until simultaneously both `cond` is `true`
  286. // and this `Mutex` can be reacquired, then reacquires this `Mutex` in the
  287. // same mode in which it was previously held. If the condition is initially
  288. // `true`, `Await()` *may* skip the release/re-acquire step.
  289. //
  290. // `Await()` requires that this thread holds this `Mutex` in some mode.
  291. void Await(const Condition& cond);
  292. // Mutex::LockWhen()
  293. // Mutex::ReaderLockWhen()
  294. // Mutex::WriterLockWhen()
  295. //
  296. // Blocks until simultaneously both `cond` is `true` and this `Mutex` can
  297. // be acquired, then atomically acquires this `Mutex`. `LockWhen()` is
  298. // logically equivalent to `*Lock(); Await();` though they may have different
  299. // performance characteristics.
  300. void LockWhen(const Condition& cond) ABSL_EXCLUSIVE_LOCK_FUNCTION();
  301. void ReaderLockWhen(const Condition& cond) ABSL_SHARED_LOCK_FUNCTION();
  302. void WriterLockWhen(const Condition& cond) ABSL_EXCLUSIVE_LOCK_FUNCTION()
  303. {
  304. this->LockWhen(cond);
  305. }
  306. // ---------------------------------------------------------------------------
  307. // Mutex Variants with Timeouts/Deadlines
  308. // ---------------------------------------------------------------------------
  309. // Mutex::AwaitWithTimeout()
  310. // Mutex::AwaitWithDeadline()
  311. //
  312. // Unlocks this `Mutex` and blocks until simultaneously:
  313. // - either `cond` is true or the {timeout has expired, deadline has passed}
  314. // and
  315. // - this `Mutex` can be reacquired,
  316. // then reacquire this `Mutex` in the same mode in which it was previously
  317. // held, returning `true` iff `cond` is `true` on return.
  318. //
  319. // If the condition is initially `true`, the implementation *may* skip the
  320. // release/re-acquire step and return immediately.
  321. //
  322. // Deadlines in the past are equivalent to an immediate deadline.
  323. // Negative timeouts are equivalent to a zero timeout.
  324. //
  325. // This method requires that this thread holds this `Mutex` in some mode.
  326. bool AwaitWithTimeout(const Condition& cond, absl::Duration timeout);
  327. bool AwaitWithDeadline(const Condition& cond, absl::Time deadline);
  328. // Mutex::LockWhenWithTimeout()
  329. // Mutex::ReaderLockWhenWithTimeout()
  330. // Mutex::WriterLockWhenWithTimeout()
  331. //
  332. // Blocks until simultaneously both:
  333. // - either `cond` is `true` or the timeout has expired, and
  334. // - this `Mutex` can be acquired,
  335. // then atomically acquires this `Mutex`, returning `true` iff `cond` is
  336. // `true` on return.
  337. //
  338. // Negative timeouts are equivalent to a zero timeout.
  339. bool LockWhenWithTimeout(const Condition& cond, absl::Duration timeout)
  340. ABSL_EXCLUSIVE_LOCK_FUNCTION();
  341. bool ReaderLockWhenWithTimeout(const Condition& cond, absl::Duration timeout)
  342. ABSL_SHARED_LOCK_FUNCTION();
  343. bool WriterLockWhenWithTimeout(const Condition& cond, absl::Duration timeout)
  344. ABSL_EXCLUSIVE_LOCK_FUNCTION()
  345. {
  346. return this->LockWhenWithTimeout(cond, timeout);
  347. }
  348. // Mutex::LockWhenWithDeadline()
  349. // Mutex::ReaderLockWhenWithDeadline()
  350. // Mutex::WriterLockWhenWithDeadline()
  351. //
  352. // Blocks until simultaneously both:
  353. // - either `cond` is `true` or the deadline has been passed, and
  354. // - this `Mutex` can be acquired,
  355. // then atomically acquires this Mutex, returning `true` iff `cond` is `true`
  356. // on return.
  357. //
  358. // Deadlines in the past are equivalent to an immediate deadline.
  359. bool LockWhenWithDeadline(const Condition& cond, absl::Time deadline)
  360. ABSL_EXCLUSIVE_LOCK_FUNCTION();
  361. bool ReaderLockWhenWithDeadline(const Condition& cond, absl::Time deadline)
  362. ABSL_SHARED_LOCK_FUNCTION();
  363. bool WriterLockWhenWithDeadline(const Condition& cond, absl::Time deadline)
  364. ABSL_EXCLUSIVE_LOCK_FUNCTION()
  365. {
  366. return this->LockWhenWithDeadline(cond, deadline);
  367. }
  368. // ---------------------------------------------------------------------------
  369. // Debug Support: Invariant Checking, Deadlock Detection, Logging.
  370. // ---------------------------------------------------------------------------
  371. // Mutex::EnableInvariantDebugging()
  372. //
  373. // If `invariant`!=null and if invariant debugging has been enabled globally,
  374. // cause `(*invariant)(arg)` to be called at moments when the invariant for
  375. // this `Mutex` should hold (for example: just after acquire, just before
  376. // release).
  377. //
  378. // The routine `invariant` should have no side-effects since it is not
  379. // guaranteed how many times it will be called; it should check the invariant
  380. // and crash if it does not hold. Enabling global invariant debugging may
  381. // substantially reduce `Mutex` performance; it should be set only for
  382. // non-production runs. Optimization options may also disable invariant
  383. // checks.
  384. void EnableInvariantDebugging(void (*invariant)(void*), void* arg);
  385. // Mutex::EnableDebugLog()
  386. //
  387. // Cause all subsequent uses of this `Mutex` to be logged via
  388. // `ABSL_RAW_LOG(INFO)`. Log entries are tagged with `name` if no previous
  389. // call to `EnableInvariantDebugging()` or `EnableDebugLog()` has been made.
  390. //
  391. // Note: This method substantially reduces `Mutex` performance.
  392. void EnableDebugLog(const char* name);
  393. // Deadlock detection
  394. // Mutex::ForgetDeadlockInfo()
  395. //
  396. // Forget any deadlock-detection information previously gathered
  397. // about this `Mutex`. Call this method in debug mode when the lock ordering
  398. // of a `Mutex` changes.
  399. void ForgetDeadlockInfo();
  400. // Mutex::AssertNotHeld()
  401. //
  402. // Return immediately if this thread does not hold this `Mutex` in any
  403. // mode; otherwise, may report an error (typically by crashing with a
  404. // diagnostic), or may return immediately.
  405. //
  406. // Currently this check is performed only if all of:
  407. // - in debug mode
  408. // - SetMutexDeadlockDetectionMode() has been set to kReport or kAbort
  409. // - number of locks concurrently held by this thread is not large.
  410. // are true.
  411. void AssertNotHeld() const;
  412. // Special cases.
  413. // A `MuHow` is a constant that indicates how a lock should be acquired.
  414. // Internal implementation detail. Clients should ignore.
  415. typedef const struct MuHowS* MuHow;
  416. // Mutex::InternalAttemptToUseMutexInFatalSignalHandler()
  417. //
  418. // Causes the `Mutex` implementation to prepare itself for re-entry caused by
  419. // future use of `Mutex` within a fatal signal handler. This method is
  420. // intended for use only for last-ditch attempts to log crash information.
  421. // It does not guarantee that attempts to use Mutexes within the handler will
  422. // not deadlock; it merely makes other faults less likely.
  423. //
  424. // WARNING: This routine must be invoked from a signal handler, and the
  425. // signal handler must either loop forever or terminate the process.
  426. // Attempts to return from (or `longjmp` out of) the signal handler once this
  427. // call has been made may cause arbitrary program behaviour including
  428. // crashes and deadlocks.
  429. static void InternalAttemptToUseMutexInFatalSignalHandler();
  430. private:
  431. std::atomic<intptr_t> mu_; // The Mutex state.
  432. // Post()/Wait() versus associated PerThreadSem; in class for required
  433. // friendship with PerThreadSem.
  434. static void IncrementSynchSem(Mutex* mu, base_internal::PerThreadSynch* w);
  435. static bool DecrementSynchSem(Mutex* mu, base_internal::PerThreadSynch* w, synchronization_internal::KernelTimeout t);
  436. // slow path acquire
  437. void LockSlowLoop(SynchWaitParams* waitp, int flags);
  438. // wrappers around LockSlowLoop()
  439. bool LockSlowWithDeadline(MuHow how, const Condition* cond, synchronization_internal::KernelTimeout t, int flags);
  440. void LockSlow(MuHow how, const Condition* cond, int flags) ABSL_ATTRIBUTE_COLD;
  441. // slow path release
  442. void UnlockSlow(SynchWaitParams* waitp) ABSL_ATTRIBUTE_COLD;
  443. // Common code between Await() and AwaitWithTimeout/Deadline()
  444. bool AwaitCommon(const Condition& cond, synchronization_internal::KernelTimeout t);
  445. // Attempt to remove thread s from queue.
  446. void TryRemove(base_internal::PerThreadSynch* s);
  447. // Block a thread on mutex.
  448. void Block(base_internal::PerThreadSynch* s);
  449. // Wake a thread; return successor.
  450. base_internal::PerThreadSynch* Wakeup(base_internal::PerThreadSynch* w);
  451. friend class CondVar; // for access to Trans()/Fer().
  452. void Trans(MuHow how); // used for CondVar->Mutex transfer
  453. void Fer(
  454. base_internal::PerThreadSynch* w
  455. ); // used for CondVar->Mutex transfer
  456. // Catch the error of writing Mutex when intending MutexLock.
  457. Mutex(const volatile Mutex* /*ignored*/)
  458. {
  459. } // NOLINT(runtime/explicit)
  460. Mutex(const Mutex&) = delete;
  461. Mutex& operator=(const Mutex&) = delete;
  462. };
  463. // -----------------------------------------------------------------------------
  464. // Mutex RAII Wrappers
  465. // -----------------------------------------------------------------------------
  466. // MutexLock
  467. //
  468. // `MutexLock` is a helper class, which acquires and releases a `Mutex` via
  469. // RAII.
  470. //
  471. // Example:
  472. //
  473. // Class Foo {
  474. // public:
  475. // Foo::Bar* Baz() {
  476. // MutexLock lock(&mu_);
  477. // ...
  478. // return bar;
  479. // }
  480. //
  481. // private:
  482. // Mutex mu_;
  483. // };
  484. class ABSL_SCOPED_LOCKABLE MutexLock
  485. {
  486. public:
  487. // Constructors
  488. // Calls `mu->Lock()` and returns when that call returns. That is, `*mu` is
  489. // guaranteed to be locked when this object is constructed. Requires that
  490. // `mu` be dereferenceable.
  491. explicit MutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) :
  492. mu_(mu)
  493. {
  494. this->mu_->Lock();
  495. }
  496. // Like above, but calls `mu->LockWhen(cond)` instead. That is, in addition to
  497. // the above, the condition given by `cond` is also guaranteed to hold when
  498. // this object is constructed.
  499. explicit MutexLock(Mutex* mu, const Condition& cond)
  500. ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) :
  501. mu_(mu)
  502. {
  503. this->mu_->LockWhen(cond);
  504. }
  505. MutexLock(const MutexLock&) = delete; // NOLINT(runtime/mutex)
  506. MutexLock(MutexLock&&) = delete; // NOLINT(runtime/mutex)
  507. MutexLock& operator=(const MutexLock&) = delete;
  508. MutexLock& operator=(MutexLock&&) = delete;
  509. ~MutexLock() ABSL_UNLOCK_FUNCTION()
  510. {
  511. this->mu_->Unlock();
  512. }
  513. private:
  514. Mutex* const mu_;
  515. };
  516. // ReaderMutexLock
  517. //
  518. // The `ReaderMutexLock` is a helper class, like `MutexLock`, which acquires and
  519. // releases a shared lock on a `Mutex` via RAII.
  520. class ABSL_SCOPED_LOCKABLE ReaderMutexLock
  521. {
  522. public:
  523. explicit ReaderMutexLock(Mutex* mu) ABSL_SHARED_LOCK_FUNCTION(mu) :
  524. mu_(mu)
  525. {
  526. mu->ReaderLock();
  527. }
  528. explicit ReaderMutexLock(Mutex* mu, const Condition& cond)
  529. ABSL_SHARED_LOCK_FUNCTION(mu) :
  530. mu_(mu)
  531. {
  532. mu->ReaderLockWhen(cond);
  533. }
  534. ReaderMutexLock(const ReaderMutexLock&) = delete;
  535. ReaderMutexLock(ReaderMutexLock&&) = delete;
  536. ReaderMutexLock& operator=(const ReaderMutexLock&) = delete;
  537. ReaderMutexLock& operator=(ReaderMutexLock&&) = delete;
  538. ~ReaderMutexLock() ABSL_UNLOCK_FUNCTION()
  539. {
  540. this->mu_->ReaderUnlock();
  541. }
  542. private:
  543. Mutex* const mu_;
  544. };
  545. // WriterMutexLock
  546. //
  547. // The `WriterMutexLock` is a helper class, like `MutexLock`, which acquires and
  548. // releases a write (exclusive) lock on a `Mutex` via RAII.
  549. class ABSL_SCOPED_LOCKABLE WriterMutexLock
  550. {
  551. public:
  552. explicit WriterMutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) :
  553. mu_(mu)
  554. {
  555. mu->WriterLock();
  556. }
  557. explicit WriterMutexLock(Mutex* mu, const Condition& cond)
  558. ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) :
  559. mu_(mu)
  560. {
  561. mu->WriterLockWhen(cond);
  562. }
  563. WriterMutexLock(const WriterMutexLock&) = delete;
  564. WriterMutexLock(WriterMutexLock&&) = delete;
  565. WriterMutexLock& operator=(const WriterMutexLock&) = delete;
  566. WriterMutexLock& operator=(WriterMutexLock&&) = delete;
  567. ~WriterMutexLock() ABSL_UNLOCK_FUNCTION()
  568. {
  569. this->mu_->WriterUnlock();
  570. }
  571. private:
  572. Mutex* const mu_;
  573. };
  574. // -----------------------------------------------------------------------------
  575. // Condition
  576. // -----------------------------------------------------------------------------
  577. //
  578. // As noted above, `Mutex` contains a number of member functions which take a
  579. // `Condition` as an argument; clients can wait for conditions to become `true`
  580. // before attempting to acquire the mutex. These sections are known as
  581. // "condition critical" sections. To use a `Condition`, you simply need to
  582. // construct it, and use within an appropriate `Mutex` member function;
  583. // everything else in the `Condition` class is an implementation detail.
  584. //
  585. // A `Condition` is specified as a function pointer which returns a boolean.
  586. // `Condition` functions should be pure functions -- their results should depend
  587. // only on passed arguments, should not consult any external state (such as
  588. // clocks), and should have no side-effects, aside from debug logging. Any
  589. // objects that the function may access should be limited to those which are
  590. // constant while the mutex is blocked on the condition (e.g. a stack variable),
  591. // or objects of state protected explicitly by the mutex.
  592. //
  593. // No matter which construction is used for `Condition`, the underlying
  594. // function pointer / functor / callable must not throw any
  595. // exceptions. Correctness of `Mutex` / `Condition` is not guaranteed in
  596. // the face of a throwing `Condition`. (When Abseil is allowed to depend
  597. // on C++17, these function pointers will be explicitly marked
  598. // `noexcept`; until then this requirement cannot be enforced in the
  599. // type system.)
  600. //
  601. // Note: to use a `Condition`, you need only construct it and pass it to a
  602. // suitable `Mutex' member function, such as `Mutex::Await()`, or to the
  603. // constructor of one of the scope guard classes.
  604. //
  605. // Example using LockWhen/Unlock:
  606. //
  607. // // assume count_ is not internal reference count
  608. // int count_ ABSL_GUARDED_BY(mu_);
  609. // Condition count_is_zero(+[](int *count) { return *count == 0; }, &count_);
  610. //
  611. // mu_.LockWhen(count_is_zero);
  612. // // ...
  613. // mu_.Unlock();
  614. //
  615. // Example using a scope guard:
  616. //
  617. // {
  618. // MutexLock lock(&mu_, count_is_zero);
  619. // // ...
  620. // }
  621. //
  622. // When multiple threads are waiting on exactly the same condition, make sure
  623. // that they are constructed with the same parameters (same pointer to function
  624. // + arg, or same pointer to object + method), so that the mutex implementation
  625. // can avoid redundantly evaluating the same condition for each thread.
  626. class Condition
  627. {
  628. public:
  629. // A Condition that returns the result of "(*func)(arg)"
  630. Condition(bool (*func)(void*), void* arg);
  631. // Templated version for people who are averse to casts.
  632. //
  633. // To use a lambda, prepend it with unary plus, which converts the lambda
  634. // into a function pointer:
  635. // Condition(+[](T* t) { return ...; }, arg).
  636. //
  637. // Note: lambdas in this case must contain no bound variables.
  638. //
  639. // See class comment for performance advice.
  640. template<typename T>
  641. Condition(bool (*func)(T*), T* arg);
  642. // Templated version for invoking a method that returns a `bool`.
  643. //
  644. // `Condition(object, &Class::Method)` constructs a `Condition` that evaluates
  645. // `object->Method()`.
  646. //
  647. // Implementation Note: `absl::internal::identity` is used to allow methods to
  648. // come from base classes. A simpler signature like
  649. // `Condition(T*, bool (T::*)())` does not suffice.
  650. template<typename T>
  651. Condition(T* object, bool (absl::internal::identity<T>::type::*method)());
  652. // Same as above, for const members
  653. template<typename T>
  654. Condition(const T* object, bool (absl::internal::identity<T>::type::*method)() const);
  655. // A Condition that returns the value of `*cond`
  656. explicit Condition(const bool* cond);
  657. // Templated version for invoking a functor that returns a `bool`.
  658. // This approach accepts pointers to non-mutable lambdas, `std::function`,
  659. // the result of` std::bind` and user-defined functors that define
  660. // `bool F::operator()() const`.
  661. //
  662. // Example:
  663. //
  664. // auto reached = [this, current]() {
  665. // mu_.AssertReaderHeld(); // For annotalysis.
  666. // return processed_ >= current;
  667. // };
  668. // mu_.Await(Condition(&reached));
  669. //
  670. // NOTE: never use "mu_.AssertHeld()" instead of "mu_.AssertReaderHeld()" in
  671. // the lambda as it may be called when the mutex is being unlocked from a
  672. // scope holding only a reader lock, which will make the assertion not
  673. // fulfilled and crash the binary.
  674. // See class comment for performance advice. In particular, if there
  675. // might be more than one waiter for the same condition, make sure
  676. // that all waiters construct the condition with the same pointers.
  677. // Implementation note: The second template parameter ensures that this
  678. // constructor doesn't participate in overload resolution if T doesn't have
  679. // `bool operator() const`.
  680. template<typename T, typename E = decltype(static_cast<bool (T::*)() const>(&T::operator()))>
  681. explicit Condition(const T* obj) :
  682. Condition(obj, static_cast<bool (T::*)() const>(&T::operator()))
  683. {
  684. }
  685. // A Condition that always returns `true`.
  686. static const Condition kTrue;
  687. // Evaluates the condition.
  688. bool Eval() const;
  689. // Returns `true` if the two conditions are guaranteed to return the same
  690. // value if evaluated at the same time, `false` if the evaluation *may* return
  691. // different results.
  692. //
  693. // Two `Condition` values are guaranteed equal if both their `func` and `arg`
  694. // components are the same. A null pointer is equivalent to a `true`
  695. // condition.
  696. static bool GuaranteedEqual(const Condition* a, const Condition* b);
  697. private:
  698. typedef bool (*InternalFunctionType)(void* arg);
  699. typedef bool (Condition::*InternalMethodType)();
  700. typedef bool (*InternalMethodCallerType)(void* arg, InternalMethodType internal_method);
  701. bool (*eval_)(const Condition*); // Actual evaluator
  702. InternalFunctionType function_; // function taking pointer returning bool
  703. InternalMethodType method_; // method returning bool
  704. void* arg_; // arg of function_ or object of method_
  705. Condition(); // null constructor used only to create kTrue
  706. // Various functions eval_ can point to:
  707. static bool CallVoidPtrFunction(const Condition*);
  708. template<typename T>
  709. static bool CastAndCallFunction(const Condition* c);
  710. template<typename T>
  711. static bool CastAndCallMethod(const Condition* c);
  712. };
  713. // -----------------------------------------------------------------------------
  714. // CondVar
  715. // -----------------------------------------------------------------------------
  716. //
  717. // A condition variable, reflecting state evaluated separately outside of the
  718. // `Mutex` object, which can be signaled to wake callers.
  719. // This class is not normally needed; use `Mutex` member functions such as
  720. // `Mutex::Await()` and intrinsic `Condition` abstractions. In rare cases
  721. // with many threads and many conditions, `CondVar` may be faster.
  722. //
  723. // The implementation may deliver signals to any condition variable at
  724. // any time, even when no call to `Signal()` or `SignalAll()` is made; as a
  725. // result, upon being awoken, you must check the logical condition you have
  726. // been waiting upon.
  727. //
  728. // Examples:
  729. //
  730. // Usage for a thread waiting for some condition C protected by mutex mu:
  731. // mu.Lock();
  732. // while (!C) { cv->Wait(&mu); } // releases and reacquires mu
  733. // // C holds; process data
  734. // mu.Unlock();
  735. //
  736. // Usage to wake T is:
  737. // mu.Lock();
  738. // // process data, possibly establishing C
  739. // if (C) { cv->Signal(); }
  740. // mu.Unlock();
  741. //
  742. // If C may be useful to more than one waiter, use `SignalAll()` instead of
  743. // `Signal()`.
  744. //
  745. // With this implementation it is efficient to use `Signal()/SignalAll()` inside
  746. // the locked region; this usage can make reasoning about your program easier.
  747. //
  748. class CondVar
  749. {
  750. public:
  751. // A `CondVar` allocated on the heap or on the stack can use the this
  752. // constructor.
  753. CondVar();
  754. ~CondVar();
  755. // CondVar::Wait()
  756. //
  757. // Atomically releases a `Mutex` and blocks on this condition variable.
  758. // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a
  759. // spurious wakeup), then reacquires the `Mutex` and returns.
  760. //
  761. // Requires and ensures that the current thread holds the `Mutex`.
  762. void Wait(Mutex* mu);
  763. // CondVar::WaitWithTimeout()
  764. //
  765. // Atomically releases a `Mutex` and blocks on this condition variable.
  766. // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a
  767. // spurious wakeup), or until the timeout has expired, then reacquires
  768. // the `Mutex` and returns.
  769. //
  770. // Returns true if the timeout has expired without this `CondVar`
  771. // being signalled in any manner. If both the timeout has expired
  772. // and this `CondVar` has been signalled, the implementation is free
  773. // to return `true` or `false`.
  774. //
  775. // Requires and ensures that the current thread holds the `Mutex`.
  776. bool WaitWithTimeout(Mutex* mu, absl::Duration timeout);
  777. // CondVar::WaitWithDeadline()
  778. //
  779. // Atomically releases a `Mutex` and blocks on this condition variable.
  780. // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a
  781. // spurious wakeup), or until the deadline has passed, then reacquires
  782. // the `Mutex` and returns.
  783. //
  784. // Deadlines in the past are equivalent to an immediate deadline.
  785. //
  786. // Returns true if the deadline has passed without this `CondVar`
  787. // being signalled in any manner. If both the deadline has passed
  788. // and this `CondVar` has been signalled, the implementation is free
  789. // to return `true` or `false`.
  790. //
  791. // Requires and ensures that the current thread holds the `Mutex`.
  792. bool WaitWithDeadline(Mutex* mu, absl::Time deadline);
  793. // CondVar::Signal()
  794. //
  795. // Signal this `CondVar`; wake at least one waiter if one exists.
  796. void Signal();
  797. // CondVar::SignalAll()
  798. //
  799. // Signal this `CondVar`; wake all waiters.
  800. void SignalAll();
  801. // CondVar::EnableDebugLog()
  802. //
  803. // Causes all subsequent uses of this `CondVar` to be logged via
  804. // `ABSL_RAW_LOG(INFO)`. Log entries are tagged with `name` if `name != 0`.
  805. // Note: this method substantially reduces `CondVar` performance.
  806. void EnableDebugLog(const char* name);
  807. private:
  808. bool WaitCommon(Mutex* mutex, synchronization_internal::KernelTimeout t);
  809. void Remove(base_internal::PerThreadSynch* s);
  810. void Wakeup(base_internal::PerThreadSynch* w);
  811. std::atomic<intptr_t> cv_; // Condition variable state.
  812. CondVar(const CondVar&) = delete;
  813. CondVar& operator=(const CondVar&) = delete;
  814. };
  815. // Variants of MutexLock.
  816. //
  817. // If you find yourself using one of these, consider instead using
  818. // Mutex::Unlock() and/or if-statements for clarity.
  819. // MutexLockMaybe
  820. //
  821. // MutexLockMaybe is like MutexLock, but is a no-op when mu is null.
  822. class ABSL_SCOPED_LOCKABLE MutexLockMaybe
  823. {
  824. public:
  825. explicit MutexLockMaybe(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) :
  826. mu_(mu)
  827. {
  828. if (this->mu_ != nullptr)
  829. {
  830. this->mu_->Lock();
  831. }
  832. }
  833. explicit MutexLockMaybe(Mutex* mu, const Condition& cond)
  834. ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) :
  835. mu_(mu)
  836. {
  837. if (this->mu_ != nullptr)
  838. {
  839. this->mu_->LockWhen(cond);
  840. }
  841. }
  842. ~MutexLockMaybe() ABSL_UNLOCK_FUNCTION()
  843. {
  844. if (this->mu_ != nullptr)
  845. {
  846. this->mu_->Unlock();
  847. }
  848. }
  849. private:
  850. Mutex* const mu_;
  851. MutexLockMaybe(const MutexLockMaybe&) = delete;
  852. MutexLockMaybe(MutexLockMaybe&&) = delete;
  853. MutexLockMaybe& operator=(const MutexLockMaybe&) = delete;
  854. MutexLockMaybe& operator=(MutexLockMaybe&&) = delete;
  855. };
  856. // ReleasableMutexLock
  857. //
  858. // ReleasableMutexLock is like MutexLock, but permits `Release()` of its
  859. // mutex before destruction. `Release()` may be called at most once.
  860. class ABSL_SCOPED_LOCKABLE ReleasableMutexLock
  861. {
  862. public:
  863. explicit ReleasableMutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) :
  864. mu_(mu)
  865. {
  866. this->mu_->Lock();
  867. }
  868. explicit ReleasableMutexLock(Mutex* mu, const Condition& cond)
  869. ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) :
  870. mu_(mu)
  871. {
  872. this->mu_->LockWhen(cond);
  873. }
  874. ~ReleasableMutexLock() ABSL_UNLOCK_FUNCTION()
  875. {
  876. if (this->mu_ != nullptr)
  877. {
  878. this->mu_->Unlock();
  879. }
  880. }
  881. void Release() ABSL_UNLOCK_FUNCTION();
  882. private:
  883. Mutex* mu_;
  884. ReleasableMutexLock(const ReleasableMutexLock&) = delete;
  885. ReleasableMutexLock(ReleasableMutexLock&&) = delete;
  886. ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;
  887. ReleasableMutexLock& operator=(ReleasableMutexLock&&) = delete;
  888. };
  889. inline Mutex::Mutex() :
  890. mu_(0)
  891. {
  892. ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
  893. }
  894. inline constexpr Mutex::Mutex(absl::ConstInitType) :
  895. mu_(0)
  896. {
  897. }
  898. inline CondVar::CondVar() :
  899. cv_(0)
  900. {
  901. }
  902. // static
  903. template<typename T>
  904. bool Condition::CastAndCallMethod(const Condition* c)
  905. {
  906. typedef bool (T::*MemberType)();
  907. MemberType rm = reinterpret_cast<MemberType>(c->method_);
  908. T* x = static_cast<T*>(c->arg_);
  909. return (x->*rm)();
  910. }
  911. // static
  912. template<typename T>
  913. bool Condition::CastAndCallFunction(const Condition* c)
  914. {
  915. typedef bool (*FuncType)(T*);
  916. FuncType fn = reinterpret_cast<FuncType>(c->function_);
  917. T* x = static_cast<T*>(c->arg_);
  918. return (*fn)(x);
  919. }
  920. template<typename T>
  921. inline Condition::Condition(bool (*func)(T*), T* arg) :
  922. eval_(&CastAndCallFunction<T>),
  923. function_(reinterpret_cast<InternalFunctionType>(func)),
  924. method_(nullptr),
  925. arg_(const_cast<void*>(static_cast<const void*>(arg)))
  926. {
  927. }
  928. template<typename T>
  929. inline Condition::Condition(T* object, bool (absl::internal::identity<T>::type::*method)()) :
  930. eval_(&CastAndCallMethod<T>),
  931. function_(nullptr),
  932. method_(reinterpret_cast<InternalMethodType>(method)),
  933. arg_(object)
  934. {
  935. }
  936. template<typename T>
  937. inline Condition::Condition(const T* object, bool (absl::internal::identity<T>::type::*method)() const) :
  938. eval_(&CastAndCallMethod<T>),
  939. function_(nullptr),
  940. method_(reinterpret_cast<InternalMethodType>(method)),
  941. arg_(reinterpret_cast<void*>(const_cast<T*>(object)))
  942. {
  943. }
  944. // Register a hook for profiling support.
  945. //
  946. // The function pointer registered here will be called whenever a mutex is
  947. // contended. The callback is given the cycles for which waiting happened (as
  948. // measured by //absl/base/internal/cycleclock.h, and which may not
  949. // be real "cycle" counts.)
  950. //
  951. // Calls to this function do not race or block, but there is no ordering
  952. // guaranteed between calls to this function and call to the provided hook.
  953. // In particular, the previously registered hook may still be called for some
  954. // time after this function returns.
  955. void RegisterMutexProfiler(void (*fn)(int64_t wait_cycles));
  956. // Register a hook for Mutex tracing.
  957. //
  958. // The function pointer registered here will be called whenever a mutex is
  959. // contended. The callback is given an opaque handle to the contended mutex,
  960. // an event name, and the number of wait cycles (as measured by
  961. // //absl/base/internal/cycleclock.h, and which may not be real
  962. // "cycle" counts.)
  963. //
  964. // The only event name currently sent is "slow release".
  965. //
  966. // This has the same memory ordering concerns as RegisterMutexProfiler() above.
  967. void RegisterMutexTracer(void (*fn)(const char* msg, const void* obj, int64_t wait_cycles));
  968. // TODO(gfalcon): Combine RegisterMutexProfiler() and RegisterMutexTracer()
  969. // into a single interface, since they are only ever called in pairs.
  970. // Register a hook for CondVar tracing.
  971. //
  972. // The function pointer registered here will be called here on various CondVar
  973. // events. The callback is given an opaque handle to the CondVar object and
  974. // a string identifying the event. This is thread-safe, but only a single
  975. // tracer can be registered.
  976. //
  977. // Events that can be sent are "Wait", "Unwait", "Signal wakeup", and
  978. // "SignalAll wakeup".
  979. //
  980. // This has the same memory ordering concerns as RegisterMutexProfiler() above.
  981. void RegisterCondVarTracer(void (*fn)(const char* msg, const void* cv));
  982. // Register a hook for symbolizing stack traces in deadlock detector reports.
  983. //
  984. // 'pc' is the program counter being symbolized, 'out' is the buffer to write
  985. // into, and 'out_size' is the size of the buffer. This function can return
  986. // false if symbolizing failed, or true if a NUL-terminated symbol was written
  987. // to 'out.'
  988. //
  989. // This has the same memory ordering concerns as RegisterMutexProfiler() above.
  990. //
  991. // DEPRECATED: The default symbolizer function is absl::Symbolize() and the
  992. // ability to register a different hook for symbolizing stack traces will be
  993. // removed on or after 2023-05-01.
  994. ABSL_DEPRECATED("absl::RegisterSymbolizer() is deprecated and will be removed "
  995. "on or after 2023-05-01")
  996. void RegisterSymbolizer(bool (*fn)(const void* pc, char* out, int out_size));
  997. // EnableMutexInvariantDebugging()
  998. //
  999. // Enable or disable global support for Mutex invariant debugging. If enabled,
  1000. // then invariant predicates can be registered per-Mutex for debug checking.
  1001. // See Mutex::EnableInvariantDebugging().
  1002. void EnableMutexInvariantDebugging(bool enabled);
  1003. // When in debug mode, and when the feature has been enabled globally, the
  1004. // implementation will keep track of lock ordering and complain (or optionally
  1005. // crash) if a cycle is detected in the acquired-before graph.
  1006. // Possible modes of operation for the deadlock detector in debug mode.
  1007. enum class OnDeadlockCycle
  1008. {
  1009. kIgnore, // Neither report on nor attempt to track cycles in lock ordering
  1010. kReport, // Report lock cycles to stderr when detected
  1011. kAbort, // Report lock cycles to stderr when detected, then abort
  1012. };
  1013. // SetMutexDeadlockDetectionMode()
  1014. //
  1015. // Enable or disable global support for detection of potential deadlocks
  1016. // due to Mutex lock ordering inversions. When set to 'kIgnore', tracking of
  1017. // lock ordering is disabled. Otherwise, in debug builds, a lock ordering graph
  1018. // will be maintained internally, and detected cycles will be reported in
  1019. // the manner chosen here.
  1020. void SetMutexDeadlockDetectionMode(OnDeadlockCycle mode);
  1021. ABSL_NAMESPACE_END
  1022. } // namespace absl
  1023. // In some build configurations we pass --detect-odr-violations to the
  1024. // gold linker. This causes it to flag weak symbol overrides as ODR
  1025. // violations. Because ODR only applies to C++ and not C,
  1026. // --detect-odr-violations ignores symbols not mangled with C++ names.
  1027. // By changing our extension points to be extern "C", we dodge this
  1028. // check.
  1029. extern "C"
  1030. {
  1031. void ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)();
  1032. } // extern "C"
  1033. #endif // ABSL_SYNCHRONIZATION_MUTEX_H_