Coverage Report

Created: 2026-02-14 07:09

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