• 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 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. Caller 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 inline void IncrementSynchSem(Mutex *mu,
461                                        base_internal::PerThreadSynch *w);
462   static inline bool DecrementSynchSem(
463       Mutex *mu, base_internal::PerThreadSynch *w,
464       synchronization_internal::KernelTimeout t);
465 
466   // slow path acquire
467   void LockSlowLoop(SynchWaitParams *waitp, int flags);
468   // wrappers around LockSlowLoop()
469   bool LockSlowWithDeadline(MuHow how, const Condition *cond,
470                             synchronization_internal::KernelTimeout t,
471                             int flags);
472   void LockSlow(MuHow how, const Condition *cond,
473                 int flags) ABSL_ATTRIBUTE_COLD;
474   // slow path release
475   void UnlockSlow(SynchWaitParams *waitp) ABSL_ATTRIBUTE_COLD;
476   // Common code between Await() and AwaitWithTimeout/Deadline()
477   bool AwaitCommon(const Condition &cond,
478                    synchronization_internal::KernelTimeout t);
479   // Attempt to remove thread s from queue.
480   void TryRemove(base_internal::PerThreadSynch *s);
481   // Block a thread on mutex.
482   void Block(base_internal::PerThreadSynch *s);
483   // Wake a thread; return successor.
484   base_internal::PerThreadSynch *Wakeup(base_internal::PerThreadSynch *w);
485 
486   friend class CondVar;   // for access to Trans()/Fer().
487   void Trans(MuHow how);  // used for CondVar->Mutex transfer
488   void Fer(
489       base_internal::PerThreadSynch *w);  // used for CondVar->Mutex transfer
490 
491   // Catch the error of writing Mutex when intending MutexLock.
Mutex(const volatile Mutex *)492   Mutex(const volatile Mutex * /*ignored*/) {}  // NOLINT(runtime/explicit)
493 
494   Mutex(const Mutex&) = delete;
495   Mutex& operator=(const Mutex&) = delete;
496 };
497 
498 // -----------------------------------------------------------------------------
499 // Mutex RAII Wrappers
500 // -----------------------------------------------------------------------------
501 
502 // MutexLock
503 //
504 // `MutexLock` is a helper class, which acquires and releases a `Mutex` via
505 // RAII.
506 //
507 // Example:
508 //
509 // Class Foo {
510 //  public:
511 //   Foo::Bar* Baz() {
512 //     MutexLock lock(&mu_);
513 //     ...
514 //     return bar;
515 //   }
516 //
517 // private:
518 //   Mutex mu_;
519 // };
520 class ABSL_SCOPED_LOCKABLE MutexLock {
521  public:
522   // Constructors
523 
524   // Calls `mu->Lock()` and returns when that call returns. That is, `*mu` is
525   // guaranteed to be locked when this object is constructed. Requires that
526   // `mu` be dereferenceable.
MutexLock(Mutex * mu)527   explicit MutexLock(Mutex *mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) {
528     this->mu_->Lock();
529   }
530 
531   // Like above, but calls `mu->LockWhen(cond)` instead. That is, in addition to
532   // the above, the condition given by `cond` is also guaranteed to hold when
533   // this object is constructed.
MutexLock(Mutex * mu,const Condition & cond)534   explicit MutexLock(Mutex *mu, const Condition &cond)
535       ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
536       : mu_(mu) {
537     this->mu_->LockWhen(cond);
538   }
539 
540   MutexLock(const MutexLock &) = delete;  // NOLINT(runtime/mutex)
541   MutexLock(MutexLock&&) = delete;  // NOLINT(runtime/mutex)
542   MutexLock& operator=(const MutexLock&) = delete;
543   MutexLock& operator=(MutexLock&&) = delete;
544 
ABSL_UNLOCK_FUNCTION()545   ~MutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_->Unlock(); }
546 
547  private:
548   Mutex *const mu_;
549 };
550 
551 // ReaderMutexLock
552 //
553 // The `ReaderMutexLock` is a helper class, like `MutexLock`, which acquires and
554 // releases a shared lock on a `Mutex` via RAII.
555 class ABSL_SCOPED_LOCKABLE ReaderMutexLock {
556  public:
ReaderMutexLock(Mutex * mu)557   explicit ReaderMutexLock(Mutex *mu) ABSL_SHARED_LOCK_FUNCTION(mu) : mu_(mu) {
558     mu->ReaderLock();
559   }
560 
ReaderMutexLock(Mutex * mu,const Condition & cond)561   explicit ReaderMutexLock(Mutex *mu, const Condition &cond)
562       ABSL_SHARED_LOCK_FUNCTION(mu)
563       : mu_(mu) {
564     mu->ReaderLockWhen(cond);
565   }
566 
567   ReaderMutexLock(const ReaderMutexLock&) = delete;
568   ReaderMutexLock(ReaderMutexLock&&) = delete;
569   ReaderMutexLock& operator=(const ReaderMutexLock&) = delete;
570   ReaderMutexLock& operator=(ReaderMutexLock&&) = delete;
571 
ABSL_UNLOCK_FUNCTION()572   ~ReaderMutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_->ReaderUnlock(); }
573 
574  private:
575   Mutex *const mu_;
576 };
577 
578 // WriterMutexLock
579 //
580 // The `WriterMutexLock` is a helper class, like `MutexLock`, which acquires and
581 // releases a write (exclusive) lock on a `Mutex` via RAII.
582 class ABSL_SCOPED_LOCKABLE WriterMutexLock {
583  public:
WriterMutexLock(Mutex * mu)584   explicit WriterMutexLock(Mutex *mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
585       : mu_(mu) {
586     mu->WriterLock();
587   }
588 
WriterMutexLock(Mutex * mu,const Condition & cond)589   explicit WriterMutexLock(Mutex *mu, const Condition &cond)
590       ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
591       : mu_(mu) {
592     mu->WriterLockWhen(cond);
593   }
594 
595   WriterMutexLock(const WriterMutexLock&) = delete;
596   WriterMutexLock(WriterMutexLock&&) = delete;
597   WriterMutexLock& operator=(const WriterMutexLock&) = delete;
598   WriterMutexLock& operator=(WriterMutexLock&&) = delete;
599 
ABSL_UNLOCK_FUNCTION()600   ~WriterMutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_->WriterUnlock(); }
601 
602  private:
603   Mutex *const mu_;
604 };
605 
606 // -----------------------------------------------------------------------------
607 // Condition
608 // -----------------------------------------------------------------------------
609 //
610 // As noted above, `Mutex` contains a number of member functions which take a
611 // `Condition` as an argument; clients can wait for conditions to become `true`
612 // before attempting to acquire the mutex. These sections are known as
613 // "condition critical" sections. To use a `Condition`, you simply need to
614 // construct it, and use within an appropriate `Mutex` member function;
615 // everything else in the `Condition` class is an implementation detail.
616 //
617 // A `Condition` is specified as a function pointer which returns a boolean.
618 // `Condition` functions should be pure functions -- their results should depend
619 // only on passed arguments, should not consult any external state (such as
620 // clocks), and should have no side-effects, aside from debug logging. Any
621 // objects that the function may access should be limited to those which are
622 // constant while the mutex is blocked on the condition (e.g. a stack variable),
623 // or objects of state protected explicitly by the mutex.
624 //
625 // No matter which construction is used for `Condition`, the underlying
626 // function pointer / functor / callable must not throw any
627 // exceptions. Correctness of `Mutex` / `Condition` is not guaranteed in
628 // the face of a throwing `Condition`. (When Abseil is allowed to depend
629 // on C++17, these function pointers will be explicitly marked
630 // `noexcept`; until then this requirement cannot be enforced in the
631 // type system.)
632 //
633 // Note: to use a `Condition`, you need only construct it and pass it to a
634 // suitable `Mutex' member function, such as `Mutex::Await()`, or to the
635 // constructor of one of the scope guard classes.
636 //
637 // Example using LockWhen/Unlock:
638 //
639 //   // assume count_ is not internal reference count
640 //   int count_ ABSL_GUARDED_BY(mu_);
641 //   Condition count_is_zero(+[](int *count) { return *count == 0; }, &count_);
642 //
643 //   mu_.LockWhen(count_is_zero);
644 //   // ...
645 //   mu_.Unlock();
646 //
647 // Example using a scope guard:
648 //
649 //   {
650 //     MutexLock lock(&mu_, count_is_zero);
651 //     // ...
652 //   }
653 //
654 // When multiple threads are waiting on exactly the same condition, make sure
655 // that they are constructed with the same parameters (same pointer to function
656 // + arg, or same pointer to object + method), so that the mutex implementation
657 // can avoid redundantly evaluating the same condition for each thread.
658 class Condition {
659  public:
660   // A Condition that returns the result of "(*func)(arg)"
661   Condition(bool (*func)(void *), void *arg);
662 
663   // Templated version for people who are averse to casts.
664   //
665   // To use a lambda, prepend it with unary plus, which converts the lambda
666   // into a function pointer:
667   //     Condition(+[](T* t) { return ...; }, arg).
668   //
669   // Note: lambdas in this case must contain no bound variables.
670   //
671   // See class comment for performance advice.
672   template<typename T>
673   Condition(bool (*func)(T *), T *arg);
674 
675   // Templated version for invoking a method that returns a `bool`.
676   //
677   // `Condition(object, &Class::Method)` constructs a `Condition` that evaluates
678   // `object->Method()`.
679   //
680   // Implementation Note: `absl::internal::identity` is used to allow methods to
681   // come from base classes. A simpler signature like
682   // `Condition(T*, bool (T::*)())` does not suffice.
683   template<typename T>
684   Condition(T *object, bool (absl::internal::identity<T>::type::* method)());
685 
686   // Same as above, for const members
687   template<typename T>
688   Condition(const T *object,
689             bool (absl::internal::identity<T>::type::* method)() const);
690 
691   // A Condition that returns the value of `*cond`
692   explicit Condition(const bool *cond);
693 
694   // Templated version for invoking a functor that returns a `bool`.
695   // This approach accepts pointers to non-mutable lambdas, `std::function`,
696   // the result of` std::bind` and user-defined functors that define
697   // `bool F::operator()() const`.
698   //
699   // Example:
700   //
701   //   auto reached = [this, current]() {
702   //     mu_.AssertReaderHeld();                // For annotalysis.
703   //     return processed_ >= current;
704   //   };
705   //   mu_.Await(Condition(&reached));
706   //
707   // NOTE: never use "mu_.AssertHeld()" instead of "mu_.AssertReaderHeld()" in
708   // the lambda as it may be called when the mutex is being unlocked from a
709   // scope holding only a reader lock, which will make the assertion not
710   // fulfilled and crash the binary.
711 
712   // See class comment for performance advice. In particular, if there
713   // might be more than one waiter for the same condition, make sure
714   // that all waiters construct the condition with the same pointers.
715 
716   // Implementation note: The second template parameter ensures that this
717   // constructor doesn't participate in overload resolution if T doesn't have
718   // `bool operator() const`.
719   template <typename T, typename E = decltype(
720       static_cast<bool (T::*)() const>(&T::operator()))>
Condition(const T * obj)721   explicit Condition(const T *obj)
722       : Condition(obj, static_cast<bool (T::*)() const>(&T::operator())) {}
723 
724   // A Condition that always returns `true`.
725   static const Condition kTrue;
726 
727   // Evaluates the condition.
728   bool Eval() const;
729 
730   // Returns `true` if the two conditions are guaranteed to return the same
731   // value if evaluated at the same time, `false` if the evaluation *may* return
732   // different results.
733   //
734   // Two `Condition` values are guaranteed equal if both their `func` and `arg`
735   // components are the same. A null pointer is equivalent to a `true`
736   // condition.
737   static bool GuaranteedEqual(const Condition *a, const Condition *b);
738 
739  private:
740   typedef bool (*InternalFunctionType)(void * arg);
741   typedef bool (Condition::*InternalMethodType)();
742   typedef bool (*InternalMethodCallerType)(void * arg,
743                                            InternalMethodType internal_method);
744 
745   bool (*eval_)(const Condition*);  // Actual evaluator
746   InternalFunctionType function_;   // function taking pointer returning bool
747   InternalMethodType method_;       // method returning bool
748   void *arg_;                       // arg of function_ or object of method_
749 
750   Condition();        // null constructor used only to create kTrue
751 
752   // Various functions eval_ can point to:
753   static bool CallVoidPtrFunction(const Condition*);
754   template <typename T> static bool CastAndCallFunction(const Condition* c);
755   template <typename T> static bool CastAndCallMethod(const Condition* c);
756 };
757 
758 // -----------------------------------------------------------------------------
759 // CondVar
760 // -----------------------------------------------------------------------------
761 //
762 // A condition variable, reflecting state evaluated separately outside of the
763 // `Mutex` object, which can be signaled to wake callers.
764 // This class is not normally needed; use `Mutex` member functions such as
765 // `Mutex::Await()` and intrinsic `Condition` abstractions. In rare cases
766 // with many threads and many conditions, `CondVar` may be faster.
767 //
768 // The implementation may deliver signals to any condition variable at
769 // any time, even when no call to `Signal()` or `SignalAll()` is made; as a
770 // result, upon being awoken, you must check the logical condition you have
771 // been waiting upon.
772 //
773 // Examples:
774 //
775 // Usage for a thread waiting for some condition C protected by mutex mu:
776 //       mu.Lock();
777 //       while (!C) { cv->Wait(&mu); }        // releases and reacquires mu
778 //       //  C holds; process data
779 //       mu.Unlock();
780 //
781 // Usage to wake T is:
782 //       mu.Lock();
783 //      // process data, possibly establishing C
784 //      if (C) { cv->Signal(); }
785 //      mu.Unlock();
786 //
787 // If C may be useful to more than one waiter, use `SignalAll()` instead of
788 // `Signal()`.
789 //
790 // With this implementation it is efficient to use `Signal()/SignalAll()` inside
791 // the locked region; this usage can make reasoning about your program easier.
792 //
793 class CondVar {
794  public:
795   // A `CondVar` allocated on the heap or on the stack can use the this
796   // constructor.
797   CondVar();
798   ~CondVar();
799 
800   // CondVar::Wait()
801   //
802   // Atomically releases a `Mutex` and blocks on this condition variable.
803   // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a
804   // spurious wakeup), then reacquires the `Mutex` and returns.
805   //
806   // Requires and ensures that the current thread holds the `Mutex`.
807   void Wait(Mutex *mu);
808 
809   // CondVar::WaitWithTimeout()
810   //
811   // Atomically releases a `Mutex` and blocks on this condition variable.
812   // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a
813   // spurious wakeup), or until the timeout has expired, then reacquires
814   // the `Mutex` and returns.
815   //
816   // Returns true if the timeout has expired without this `CondVar`
817   // being signalled in any manner. If both the timeout has expired
818   // and this `CondVar` has been signalled, the implementation is free
819   // to return `true` or `false`.
820   //
821   // Requires and ensures that the current thread holds the `Mutex`.
822   bool WaitWithTimeout(Mutex *mu, absl::Duration timeout);
823 
824   // CondVar::WaitWithDeadline()
825   //
826   // Atomically releases a `Mutex` and blocks on this condition variable.
827   // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a
828   // spurious wakeup), or until the deadline has passed, then reacquires
829   // the `Mutex` and returns.
830   //
831   // Deadlines in the past are equivalent to an immediate deadline.
832   //
833   // Returns true if the deadline has passed without this `CondVar`
834   // being signalled in any manner. If both the deadline has passed
835   // and this `CondVar` has been signalled, the implementation is free
836   // to return `true` or `false`.
837   //
838   // Requires and ensures that the current thread holds the `Mutex`.
839   bool WaitWithDeadline(Mutex *mu, absl::Time deadline);
840 
841   // CondVar::Signal()
842   //
843   // Signal this `CondVar`; wake at least one waiter if one exists.
844   void Signal();
845 
846   // CondVar::SignalAll()
847   //
848   // Signal this `CondVar`; wake all waiters.
849   void SignalAll();
850 
851   // CondVar::EnableDebugLog()
852   //
853   // Causes all subsequent uses of this `CondVar` to be logged via
854   // `ABSL_RAW_LOG(INFO)`. Log entries are tagged with `name` if `name != 0`.
855   // Note: this method substantially reduces `CondVar` performance.
856   void EnableDebugLog(const char *name);
857 
858  private:
859   bool WaitCommon(Mutex *mutex, synchronization_internal::KernelTimeout t);
860   void Remove(base_internal::PerThreadSynch *s);
861   void Wakeup(base_internal::PerThreadSynch *w);
862   std::atomic<intptr_t> cv_;  // Condition variable state.
863   CondVar(const CondVar&) = delete;
864   CondVar& operator=(const CondVar&) = delete;
865 };
866 
867 
868 // Variants of MutexLock.
869 //
870 // If you find yourself using one of these, consider instead using
871 // Mutex::Unlock() and/or if-statements for clarity.
872 
873 // MutexLockMaybe
874 //
875 // MutexLockMaybe is like MutexLock, but is a no-op when mu is null.
876 class ABSL_SCOPED_LOCKABLE MutexLockMaybe {
877  public:
MutexLockMaybe(Mutex * mu)878   explicit MutexLockMaybe(Mutex *mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
879       : mu_(mu) {
880     if (this->mu_ != nullptr) {
881       this->mu_->Lock();
882     }
883   }
884 
MutexLockMaybe(Mutex * mu,const Condition & cond)885   explicit MutexLockMaybe(Mutex *mu, const Condition &cond)
886       ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
887       : mu_(mu) {
888     if (this->mu_ != nullptr) {
889       this->mu_->LockWhen(cond);
890     }
891   }
892 
ABSL_UNLOCK_FUNCTION()893   ~MutexLockMaybe() ABSL_UNLOCK_FUNCTION() {
894     if (this->mu_ != nullptr) { this->mu_->Unlock(); }
895   }
896 
897  private:
898   Mutex *const mu_;
899   MutexLockMaybe(const MutexLockMaybe&) = delete;
900   MutexLockMaybe(MutexLockMaybe&&) = delete;
901   MutexLockMaybe& operator=(const MutexLockMaybe&) = delete;
902   MutexLockMaybe& operator=(MutexLockMaybe&&) = delete;
903 };
904 
905 // ReleasableMutexLock
906 //
907 // ReleasableMutexLock is like MutexLock, but permits `Release()` of its
908 // mutex before destruction. `Release()` may be called at most once.
909 class ABSL_SCOPED_LOCKABLE ReleasableMutexLock {
910  public:
ReleasableMutexLock(Mutex * mu)911   explicit ReleasableMutexLock(Mutex *mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
912       : mu_(mu) {
913     this->mu_->Lock();
914   }
915 
ReleasableMutexLock(Mutex * mu,const Condition & cond)916   explicit ReleasableMutexLock(Mutex *mu, const Condition &cond)
917       ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
918       : mu_(mu) {
919     this->mu_->LockWhen(cond);
920   }
921 
ABSL_UNLOCK_FUNCTION()922   ~ReleasableMutexLock() ABSL_UNLOCK_FUNCTION() {
923     if (this->mu_ != nullptr) { this->mu_->Unlock(); }
924   }
925 
926   void Release() ABSL_UNLOCK_FUNCTION();
927 
928  private:
929   Mutex *mu_;
930   ReleasableMutexLock(const ReleasableMutexLock&) = delete;
931   ReleasableMutexLock(ReleasableMutexLock&&) = delete;
932   ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;
933   ReleasableMutexLock& operator=(ReleasableMutexLock&&) = delete;
934 };
935 
Mutex()936 inline Mutex::Mutex() : mu_(0) {
937   ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
938 }
939 
Mutex(absl::ConstInitType)940 inline constexpr Mutex::Mutex(absl::ConstInitType) : mu_(0) {}
941 
CondVar()942 inline CondVar::CondVar() : cv_(0) {}
943 
944 // static
945 template <typename T>
CastAndCallMethod(const Condition * c)946 bool Condition::CastAndCallMethod(const Condition *c) {
947   typedef bool (T::*MemberType)();
948   MemberType rm = reinterpret_cast<MemberType>(c->method_);
949   T *x = static_cast<T *>(c->arg_);
950   return (x->*rm)();
951 }
952 
953 // static
954 template <typename T>
CastAndCallFunction(const Condition * c)955 bool Condition::CastAndCallFunction(const Condition *c) {
956   typedef bool (*FuncType)(T *);
957   FuncType fn = reinterpret_cast<FuncType>(c->function_);
958   T *x = static_cast<T *>(c->arg_);
959   return (*fn)(x);
960 }
961 
962 template <typename T>
Condition(bool (* func)(T *),T * arg)963 inline Condition::Condition(bool (*func)(T *), T *arg)
964     : eval_(&CastAndCallFunction<T>),
965       function_(reinterpret_cast<InternalFunctionType>(func)),
966       method_(nullptr),
967       arg_(const_cast<void *>(static_cast<const void *>(arg))) {}
968 
969 template <typename T>
Condition(T * object,bool (absl::internal::identity<T>::type::* method)())970 inline Condition::Condition(T *object,
971                             bool (absl::internal::identity<T>::type::*method)())
972     : eval_(&CastAndCallMethod<T>),
973       function_(nullptr),
974       method_(reinterpret_cast<InternalMethodType>(method)),
975       arg_(object) {}
976 
977 template <typename T>
Condition(const T * object,bool (absl::internal::identity<T>::type::* method)()const)978 inline Condition::Condition(const T *object,
979                             bool (absl::internal::identity<T>::type::*method)()
980                                 const)
981     : eval_(&CastAndCallMethod<T>),
982       function_(nullptr),
983       method_(reinterpret_cast<InternalMethodType>(method)),
984       arg_(reinterpret_cast<void *>(const_cast<T *>(object))) {}
985 
986 // Register a hook for profiling support.
987 //
988 // The function pointer registered here will be called whenever a mutex is
989 // contended.  The callback is given the absl/base/cycleclock.h timestamp when
990 // waiting began.
991 //
992 // Calls to this function do not race or block, but there is no ordering
993 // guaranteed between calls to this function and call to the provided hook.
994 // In particular, the previously registered hook may still be called for some
995 // time after this function returns.
996 void RegisterMutexProfiler(void (*fn)(int64_t wait_timestamp));
997 
998 // Register a hook for Mutex tracing.
999 //
1000 // The function pointer registered here will be called whenever a mutex is
1001 // contended.  The callback is given an opaque handle to the contended mutex,
1002 // an event name, and the number of wait cycles (as measured by
1003 // //absl/base/internal/cycleclock.h, and which may not be real
1004 // "cycle" counts.)
1005 //
1006 // The only event name currently sent is "slow release".
1007 //
1008 // This has the same memory ordering concerns as RegisterMutexProfiler() above.
1009 void RegisterMutexTracer(void (*fn)(const char *msg, const void *obj,
1010                                     int64_t wait_cycles));
1011 
1012 // TODO(gfalcon): Combine RegisterMutexProfiler() and RegisterMutexTracer()
1013 // into a single interface, since they are only ever called in pairs.
1014 
1015 // Register a hook for CondVar tracing.
1016 //
1017 // The function pointer registered here will be called here on various CondVar
1018 // events.  The callback is given an opaque handle to the CondVar object and
1019 // a string identifying the event.  This is thread-safe, but only a single
1020 // tracer can be registered.
1021 //
1022 // Events that can be sent are "Wait", "Unwait", "Signal wakeup", and
1023 // "SignalAll wakeup".
1024 //
1025 // This has the same memory ordering concerns as RegisterMutexProfiler() above.
1026 void RegisterCondVarTracer(void (*fn)(const char *msg, const void *cv));
1027 
1028 // Register a hook for symbolizing stack traces in deadlock detector reports.
1029 //
1030 // 'pc' is the program counter being symbolized, 'out' is the buffer to write
1031 // into, and 'out_size' is the size of the buffer.  This function can return
1032 // false if symbolizing failed, or true if a NUL-terminated symbol was written
1033 // to 'out.'
1034 //
1035 // This has the same memory ordering concerns as RegisterMutexProfiler() above.
1036 //
1037 // DEPRECATED: The default symbolizer function is absl::Symbolize() and the
1038 // ability to register a different hook for symbolizing stack traces will be
1039 // removed on or after 2023-05-01.
1040 ABSL_DEPRECATED("absl::RegisterSymbolizer() is deprecated and will be removed "
1041                 "on or after 2023-05-01")
1042 void RegisterSymbolizer(bool (*fn)(const void *pc, char *out, int out_size));
1043 
1044 // EnableMutexInvariantDebugging()
1045 //
1046 // Enable or disable global support for Mutex invariant debugging.  If enabled,
1047 // then invariant predicates can be registered per-Mutex for debug checking.
1048 // See Mutex::EnableInvariantDebugging().
1049 void EnableMutexInvariantDebugging(bool enabled);
1050 
1051 // When in debug mode, and when the feature has been enabled globally, the
1052 // implementation will keep track of lock ordering and complain (or optionally
1053 // crash) if a cycle is detected in the acquired-before graph.
1054 
1055 // Possible modes of operation for the deadlock detector in debug mode.
1056 enum class OnDeadlockCycle {
1057   kIgnore,  // Neither report on nor attempt to track cycles in lock ordering
1058   kReport,  // Report lock cycles to stderr when detected
1059   kAbort,  // Report lock cycles to stderr when detected, then abort
1060 };
1061 
1062 // SetMutexDeadlockDetectionMode()
1063 //
1064 // Enable or disable global support for detection of potential deadlocks
1065 // due to Mutex lock ordering inversions.  When set to 'kIgnore', tracking of
1066 // lock ordering is disabled.  Otherwise, in debug builds, a lock ordering graph
1067 // will be maintained internally, and detected cycles will be reported in
1068 // the manner chosen here.
1069 void SetMutexDeadlockDetectionMode(OnDeadlockCycle mode);
1070 
1071 ABSL_NAMESPACE_END
1072 }  // namespace absl
1073 
1074 // In some build configurations we pass --detect-odr-violations to the
1075 // gold linker.  This causes it to flag weak symbol overrides as ODR
1076 // violations.  Because ODR only applies to C++ and not C,
1077 // --detect-odr-violations ignores symbols not mangled with C++ names.
1078 // By changing our extension points to be extern "C", we dodge this
1079 // check.
1080 extern "C" {
1081 void AbslInternalMutexYield();
1082 }  // extern "C"
1083 
1084 #endif  // ABSL_SYNCHRONIZATION_MUTEX_H_
1085