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 44 kB

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