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