mutex.h 46 KB

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