Coverage Report

Created: 2026-10-28 06:49

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
  ABSL_ATTRIBUTE_COLD void LockSlow(MuHow absl_nonnull how,
563
                                    const Condition* absl_nullable cond,
564
                                    int flags);
565
  // slow path release
566
  ABSL_ATTRIBUTE_COLD void UnlockSlow(SynchWaitParams* absl_nullable waitp);
567
  // TryLock slow path.
568
  bool TryLockSlow();
569
  // ReaderTryLock slow path.
570
  bool ReaderTryLockSlow();
571
  // Common code between Await() and AwaitWithTimeout/Deadline()
572
  bool AwaitCommon(const Condition& cond,
573
                   synchronization_internal::KernelTimeout t);
574
  bool LockWhenCommon(const Condition& cond,
575
                      synchronization_internal::KernelTimeout t, bool write);
576
  // Attempt to remove thread s from queue.
577
  void TryRemove(base_internal::PerThreadSynch* absl_nonnull s);
578
  // Block a thread on mutex.
579
  void Block(base_internal::PerThreadSynch* absl_nonnull s);
580
  // Wake a thread; return successor.
581
  base_internal::PerThreadSynch* absl_nullable Wakeup(
582
      base_internal::PerThreadSynch* absl_nonnull w);
583
  void Dtor();
584
585
  friend class CondVar;                // for access to Trans()/Fer().
586
  void Trans(MuHow absl_nonnull how);  // used for CondVar->Mutex transfer
587
  void Fer(base_internal::PerThreadSynch* absl_nonnull
588
               w);  // used for CondVar->Mutex transfer
589
590
  // Catch the error of writing Mutex when intending MutexLock.
591
0
  explicit Mutex(const volatile Mutex* absl_nullable /*ignored*/) {}
592
593
  Mutex(const Mutex&) = delete;
594
  Mutex& operator=(const Mutex&) = delete;
595
};
596
597
// -----------------------------------------------------------------------------
598
// Mutex RAII Wrappers
599
// -----------------------------------------------------------------------------
600
601
// MutexLock
602
//
603
// `MutexLock` is a helper class, which acquires and releases a `Mutex` via
604
// RAII.
605
//
606
// Example:
607
//
608
// Class Foo {
609
//  public:
610
//   Foo::Bar* Baz() {
611
//     MutexLock lock(mu_);
612
//     ...
613
//     return bar;
614
//   }
615
//
616
// private:
617
//   Mutex mu_;
618
// };
619
class ABSL_SCOPED_LOCKABLE MutexLock {
620
 public:
621
  // Constructors
622
623
  // Calls `mu.lock()` and returns when that call returns. That is, `mu` is
624
  // guaranteed to be locked when this object is constructed.
625
  explicit MutexLock(Mutex& mu ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY_THIS)
626
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
627
0
      : mu_(mu) {
628
0
    this->mu_.lock();
629
0
  }
630
631
  // Calls `mu->lock()` and returns when that call returns. That is, `*mu` is
632
  // guaranteed to be locked when this object is constructed. Requires that
633
  // `mu` be dereferenceable.
634
  [[deprecated("Use the constructor that takes a reference instead")]]
635
  ABSL_REFACTOR_INLINE
636
  explicit MutexLock(Mutex* absl_nonnull mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
637
0
      : MutexLock(*mu) {}
638
639
  // Like above, but calls `mu.LockWhen(cond)` instead. That is, in addition to
640
  // the above, the condition given by `cond` is also guaranteed to hold when
641
  // this object is constructed.
642
  explicit MutexLock(Mutex& mu ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY_THIS,
643
                     const Condition& cond) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
644
0
      : mu_(mu) {
645
0
    this->mu_.LockWhen(cond);
646
0
  }
647
648
  [[deprecated("Use the constructor that takes a reference instead")]]
649
  ABSL_REFACTOR_INLINE
650
  explicit MutexLock(Mutex* absl_nonnull mu, const Condition& cond)
651
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
652
0
      : MutexLock(*mu, cond) {}
653
654
  MutexLock(const MutexLock&) = delete;  // NOLINT(runtime/mutex)
655
  MutexLock(MutexLock&&) = delete;       // NOLINT(runtime/mutex)
656
  MutexLock& operator=(const MutexLock&) = delete;
657
  MutexLock& operator=(MutexLock&&) = delete;
658
659
0
  ~MutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_.unlock(); }
660
661
 private:
662
  Mutex& mu_;
663
};
664
665
// ReaderMutexLock
666
//
667
// The `ReaderMutexLock` is a helper class, like `MutexLock`, which acquires and
668
// releases a shared lock on a `Mutex` via RAII.
669
class ABSL_SCOPED_LOCKABLE ReaderMutexLock {
670
 public:
671
  explicit ReaderMutexLock(Mutex& mu ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY_THIS)
672
      ABSL_SHARED_LOCK_FUNCTION(mu)
673
0
      : mu_(mu) {
674
0
    mu.lock_shared();
675
0
  }
676
677
  [[deprecated("Use the constructor that takes a reference instead")]]
678
  ABSL_REFACTOR_INLINE
679
  explicit ReaderMutexLock(Mutex* absl_nonnull mu) ABSL_SHARED_LOCK_FUNCTION(mu)
680
0
      : ReaderMutexLock(*mu) {}
681
682
  explicit ReaderMutexLock(Mutex& mu ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY_THIS,
683
                           const Condition& cond) ABSL_SHARED_LOCK_FUNCTION(mu)
684
0
      : mu_(mu) {
685
0
    mu.ReaderLockWhen(cond);
686
0
  }
687
688
  [[deprecated("Use the constructor that takes a reference instead")]]
689
  ABSL_REFACTOR_INLINE
690
  explicit ReaderMutexLock(Mutex* absl_nonnull mu, const Condition& cond)
691
      ABSL_SHARED_LOCK_FUNCTION(mu)
692
0
      : ReaderMutexLock(*mu, cond) {}
693
694
  ReaderMutexLock(const ReaderMutexLock&) = delete;
695
  ReaderMutexLock(ReaderMutexLock&&) = delete;
696
  ReaderMutexLock& operator=(const ReaderMutexLock&) = delete;
697
  ReaderMutexLock& operator=(ReaderMutexLock&&) = delete;
698
699
0
  ~ReaderMutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_.unlock_shared(); }
700
701
 private:
702
  Mutex& mu_;
703
};
704
705
// WriterMutexLock
706
//
707
// The `WriterMutexLock` is a helper class, like `MutexLock`, which acquires and
708
// releases a write (exclusive) lock on a `Mutex` via RAII.
709
class ABSL_SCOPED_LOCKABLE WriterMutexLock {
710
 public:
711
  explicit WriterMutexLock(Mutex& mu ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY_THIS)
712
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
713
0
      : mu_(mu) {
714
0
    mu.lock();
715
0
  }
716
717
  [[deprecated("Use the constructor that takes a reference instead")]]
718
  ABSL_REFACTOR_INLINE
719
  explicit WriterMutexLock(Mutex* absl_nonnull mu)
720
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
721
0
      : WriterMutexLock(*mu) {}
722
723
  explicit WriterMutexLock(Mutex& mu ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY_THIS,
724
                           const Condition& cond)
725
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
726
0
      : mu_(mu) {
727
0
    mu.WriterLockWhen(cond);
728
0
  }
729
730
  [[deprecated("Use the constructor that takes a reference instead")]]
731
  ABSL_REFACTOR_INLINE
732
  explicit WriterMutexLock(Mutex* absl_nonnull mu, const Condition& cond)
733
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
734
0
      : WriterMutexLock(*mu, cond) {}
735
736
  WriterMutexLock(const WriterMutexLock&) = delete;
737
  WriterMutexLock(WriterMutexLock&&) = delete;
738
  WriterMutexLock& operator=(const WriterMutexLock&) = delete;
739
  WriterMutexLock& operator=(WriterMutexLock&&) = delete;
740
741
0
  ~WriterMutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_.unlock(); }
742
743
 private:
744
  Mutex& mu_;
745
};
746
747
// -----------------------------------------------------------------------------
748
// Condition
749
// -----------------------------------------------------------------------------
750
//
751
// `Mutex` contains a number of member functions which take a `Condition` as an
752
// argument; clients can wait for conditions to become `true` before attempting
753
// to acquire the mutex. These sections are known as "condition critical"
754
// sections. To use a `Condition`, you simply need to construct it, and use
755
// within an appropriate `Mutex` member function; everything else in the
756
// `Condition` class is an implementation detail.
757
//
758
// A `Condition` is specified as a function pointer which returns a boolean.
759
// `Condition` functions should be pure functions -- their results should depend
760
// only on passed arguments, should not consult any external state (such as
761
// clocks), and should have no side-effects, aside from debug logging. Any
762
// objects that the function may access should be limited to those which are
763
// constant while the mutex is blocked on the condition (e.g. a stack variable),
764
// or objects of state protected explicitly by the mutex.
765
//
766
// No matter which construction is used for `Condition`, the underlying
767
// function pointer / functor / callable must not throw any
768
// exceptions. Correctness of `Mutex` / `Condition` is not guaranteed in
769
// the face of a throwing `Condition`. (When Abseil is allowed to depend
770
// on C++17, these function pointers will be explicitly marked
771
// `noexcept`; until then this requirement cannot be enforced in the
772
// type system.)
773
//
774
// Note: to use a `Condition`, you need only construct it and pass it to a
775
// suitable `Mutex' member function, such as `Mutex::Await()`, or to the
776
// constructor of one of the scope guard classes.
777
//
778
// Example using LockWhen/Unlock:
779
//
780
//   // assume count_ is not internal reference count
781
//   int count_ ABSL_GUARDED_BY(mu_);
782
//   Condition count_is_zero(+[](int *count) { return *count == 0; }, &count_);
783
//
784
//   mu_.LockWhen(count_is_zero);
785
//   // ...
786
//   mu_.Unlock();
787
//
788
// Example using a scope guard:
789
//
790
//   {
791
//     MutexLock lock(mu_, count_is_zero);
792
//     // ...
793
//   }
794
//
795
// When multiple threads are waiting on exactly the same condition, make sure
796
// that they are constructed with the same parameters (same pointer to function
797
// + arg, or same pointer to object + method), so that the mutex implementation
798
// can avoid redundantly evaluating the same condition for each thread.
799
class Condition {
800
 public:
801
  // A Condition that returns the result of "(*func)(arg)"
802
  Condition(bool (*absl_nonnull func)(void* absl_nullability_unknown),
803
            void* absl_nullability_unknown arg);
804
805
  // Templated version for people who are averse to casts.
806
  //
807
  // To use a lambda, prepend it with unary plus, which converts the lambda
808
  // into a function pointer:
809
  //     Condition(+[](T* t) { return ...; }, arg).
810
  //
811
  // Note: lambdas in this case must contain no bound variables.
812
  //
813
  // See class comment for performance advice.
814
  template <typename T>
815
  Condition(bool (*absl_nonnull func)(T* absl_nullability_unknown),
816
            T* absl_nullability_unknown arg);
817
818
  // Same as above, but allows for cases where `arg` comes from a pointer that
819
  // is convertible to the function parameter type `T*` but not an exact match.
820
  //
821
  // For example, the argument might be `X*` but the function takes `const X*`,
822
  // or the argument might be `Derived*` while the function takes `Base*`, and
823
  // so on for cases where the argument pointer can be implicitly converted.
824
  //
825
  // Implementation notes: This constructor overload is required in addition to
826
  // the one above to allow deduction of `T` from `arg` for cases such as where
827
  // a function template is passed as `func`. Also, the dummy `typename = void`
828
  // template parameter exists just to work around a MSVC mangling bug.
829
  template <typename T, typename = void>
830
  Condition(
831
      bool (*absl_nonnull func)(T* absl_nullability_unknown),
832
      typename absl::type_identity<T>::type* absl_nullability_unknown
833
          arg);
834
835
  // Templated version for invoking a method that returns a `bool`.
836
  //
837
  // `Condition(object, &Class::Method)` constructs a `Condition` that evaluates
838
  // `object->Method()`.
839
  //
840
  // Implementation Note: `absl::type_identity` is used to allow
841
  // methods to come from base classes. A simpler signature like
842
  // `Condition(T*, bool (T::*)())` does not suffice.
843
  template <typename T>
844
  Condition(
845
      T* absl_nonnull object,
846
      bool (absl::type_identity<T>::type::* absl_nonnull method)());
847
848
  // Same as above, for const members
849
  template <typename T>
850
  Condition(
851
      const T* absl_nonnull object,
852
      bool (absl::type_identity<T>::type::* absl_nonnull method)()
853
          const);
854
855
  // A Condition that returns the value of `*cond`
856
  explicit Condition(const bool* absl_nonnull cond);
857
858
  // Templated version for invoking a functor that returns a `bool`.
859
  // This approach accepts pointers to non-mutable lambdas, `std::function`,
860
  // the result of` std::bind` and user-defined functors that define
861
  // `bool F::operator()() const`.
862
  //
863
  // Example:
864
  //
865
  //   auto reached = [this, current]() {
866
  //     mu_.AssertReaderHeld();                // For annotalysis.
867
  //     return processed_ >= current;
868
  //   };
869
  //   mu_.Await(Condition(&reached));
870
  //
871
  // NOTE: never use "mu_.AssertHeld()" instead of "mu_.AssertReaderHeld()" in
872
  // the lambda as it may be called when the mutex is being unlocked from a
873
  // scope holding only a reader lock, which will make the assertion not
874
  // fulfilled and crash the binary.
875
876
  // See class comment for performance advice. In particular, if there
877
  // might be more than one waiter for the same condition, make sure
878
  // that all waiters construct the condition with the same pointers.
879
880
  // Implementation note: The second template parameter ensures that this
881
  // constructor doesn't participate in overload resolution if T doesn't have
882
  // `bool operator() const`.
883
  template <typename T,
884
            std::enable_if_t<
885
                synchronization_internal::HasConstMemberCallOperator<T>::value,
886
                int> = 0>
887
  explicit Condition(const T* absl_nonnull obj)
888
      : Condition(obj, static_cast<bool (T::*)() const>(&T::operator())) {}
889
890
  // Constructor for functors that do not match the `bool operator()() const`
891
  // signature, such as those using C++23 "deducing this" or static operator().
892
  template <
893
      typename T,
894
      typename = std::enable_if_t<
895
          !synchronization_internal::HasConstMemberCallOperator<T>::value &&
896
          sizeof(static_cast<bool (*)(const T&)>(&T::operator())) != 0>>
897
  explicit Condition(const T* absl_nonnull obj)
898
      : Condition(&CallByRef<T>, obj) {}
899
900
  // A Condition that always returns `true`.
901
  // kTrue is only useful in a narrow set of circumstances, mostly when
902
  // it's passed conditionally. For example:
903
  //
904
  //   mu.LockWhen(some_flag ? kTrue : SomeOtherCondition);
905
  //
906
  // Note: {LockWhen,Await}With{Deadline,Timeout} methods with kTrue condition
907
  // don't return immediately when the timeout happens, they still block until
908
  // the Mutex becomes available. The return value of these methods does
909
  // not indicate if the timeout was reached; rather it indicates whether or
910
  // not the condition is true.
911
  ABSL_CONST_INIT static const Condition kTrue;
912
913
  // Evaluates the condition.
914
  bool Eval() const;
915
916
  // Returns `true` if the two conditions are guaranteed to return the same
917
  // value if evaluated at the same time, `false` if the evaluation *may* return
918
  // different results.
919
  //
920
  // Two `Condition` values are guaranteed equal if both their `func` and `arg`
921
  // components are the same. A null pointer is equivalent to a `true`
922
  // condition.
923
  static bool GuaranteedEqual(const Condition* absl_nullable a,
924
                              const Condition* absl_nullable b);
925
926
 private:
927
  // Sizing an allocation for a method pointer can be subtle. In the Itanium
928
  // specifications, a method pointer has a predictable, uniform size. On the
929
  // other hand, MSVC ABI, method pointer sizes vary based on the
930
  // inheritance of the class. Specifically, method pointers from classes with
931
  // multiple inheritance are bigger than those of classes with single
932
  // inheritance. Other variations also exist.
933
934
#ifndef _MSC_VER
935
  // Allocation for a function pointer or method pointer.
936
  // The {0} initializer ensures that all unused bytes of this buffer are
937
  // always zeroed out.  This is necessary, because GuaranteedEqual() compares
938
  // all of the bytes, unaware of which bytes are relevant to a given `eval_`.
939
  using MethodPtr = bool (Condition::*)();
940
  char callback_[sizeof(MethodPtr)] = {0};
941
#else
942
  // It is well known that the larget MSVC pointer-to-member is 24 bytes. This
943
  // may be the largest known pointer-to-member of any platform. For this
944
  // reason we will allocate 24 bytes for MSVC platform toolchains.
945
  char callback_[24] = {0};
946
#endif
947
948
  // Function with which to evaluate callbacks and/or arguments.
949
  bool (*absl_nullable eval_)(const Condition* absl_nonnull) = nullptr;
950
951
  // Either an argument for a function call or an object for a method call.
952
  void* absl_nullable arg_ = nullptr;
953
954
  // Various functions eval_ can point to:
955
  static bool CallVoidPtrFunction(const Condition* absl_nonnull c);
956
  template <typename T>
957
  static bool CastAndCallFunction(const Condition* absl_nonnull c);
958
  template <typename T, typename ConditionMethodPtr>
959
  static bool CastAndCallMethod(const Condition* absl_nonnull c);
960
961
  template <typename T>
962
  static bool CallByRef(const T* absl_nonnull self) {
963
    return (*self)();
964
  }
965
966
  // Helper methods for storing, validating, and reading callback arguments.
967
  template <typename T>
968
0
  void StoreCallback(T callback) {
969
0
    static_assert(
970
0
        sizeof(callback) <= sizeof(callback_),
971
0
        "An overlarge pointer was passed as a callback to Condition.");
972
0
    std::memcpy(callback_, &callback, sizeof(callback));
973
0
  }
Unexecuted instantiation: void absl::Condition::StoreCallback<bool (*)(absl::SynchEvent*)>(bool (*)(absl::SynchEvent*))
Unexecuted instantiation: void absl::Condition::StoreCallback<bool (*)(void*)>(bool (*)(void*))
974
975
  template <typename T>
976
0
  void ReadCallback(T* absl_nonnull callback) const {
977
0
    std::memcpy(callback, callback_, sizeof(*callback));
978
0
  }
979
980
0
  static bool AlwaysTrue(const Condition* absl_nullable) { return true; }
981
982
  // Used only to create kTrue.
983
0
  constexpr Condition() : eval_(AlwaysTrue), arg_(nullptr) {}
984
};
985
986
// -----------------------------------------------------------------------------
987
// CondVar
988
// -----------------------------------------------------------------------------
989
//
990
// A condition variable, reflecting state evaluated separately outside of the
991
// `Mutex` object, which can be signaled to wake callers.
992
// This class is not normally needed; use `Mutex` member functions such as
993
// `Mutex::Await()` and intrinsic `Condition` abstractions. In rare cases
994
// with many threads and many conditions, `CondVar` may be faster.
995
//
996
// The implementation may deliver signals to any condition variable at
997
// any time, even when no call to `Signal()` or `SignalAll()` is made; as a
998
// result, upon being awoken, you must check the logical condition you have
999
// been waiting upon.
1000
//
1001
// Examples:
1002
//
1003
// Usage for a thread waiting for some condition C protected by mutex mu:
1004
//       mu.Lock();
1005
//       while (!C) { cv->Wait(&mu); }        // releases and reacquires mu
1006
//       //  C holds; process data
1007
//       mu.Unlock();
1008
//
1009
// Usage to wake T is:
1010
//       mu.Lock();
1011
//       // process data, possibly establishing C
1012
//       if (C) { cv->Signal(); }
1013
//       mu.Unlock();
1014
//
1015
// If C may be useful to more than one waiter, use `SignalAll()` instead of
1016
// `Signal()`.
1017
//
1018
// With this implementation it is efficient to use `Signal()/SignalAll()` inside
1019
// the locked region; this usage can make reasoning about your program easier.
1020
//
1021
class CondVar {
1022
 public:
1023
  // A `CondVar` allocated on the heap or on the stack can use the this
1024
  // constructor.
1025
  CondVar();
1026
1027
  // CondVar::Wait()
1028
  //
1029
  // Atomically releases a `Mutex` and blocks on this condition variable.
1030
  // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a
1031
  // spurious wakeup), then reacquires the `Mutex` and returns.
1032
  //
1033
  // Requires and ensures that the current thread holds the `Mutex`.
1034
0
  void Wait(Mutex* absl_nonnull mu) {
1035
0
    WaitCommon(mu, synchronization_internal::KernelTimeout::Never());
1036
0
  }
1037
1038
  // CondVar::WaitWithTimeout()
1039
  //
1040
  // Atomically releases a `Mutex` and blocks on this condition variable.
1041
  // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a
1042
  // spurious wakeup), or until the timeout has expired, then reacquires
1043
  // the `Mutex` and returns.
1044
  //
1045
  // Returns true if the timeout has expired without this `CondVar`
1046
  // being signalled in any manner. If both the timeout has expired
1047
  // and this `CondVar` has been signalled, the implementation is free
1048
  // to return `true` or `false`.
1049
  //
1050
  // Requires and ensures that the current thread holds the `Mutex`.
1051
0
  bool WaitWithTimeout(Mutex* absl_nonnull mu, absl::Duration timeout) {
1052
0
    return WaitCommon(mu, synchronization_internal::KernelTimeout(timeout));
1053
0
  }
1054
1055
  // CondVar::WaitWithDeadline()
1056
  //
1057
  // Atomically releases a `Mutex` and blocks on this condition variable.
1058
  // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a
1059
  // spurious wakeup), or until the deadline has passed, then reacquires
1060
  // the `Mutex` and returns.
1061
  //
1062
  // Deadlines in the past are equivalent to an immediate deadline.
1063
  //
1064
  // Returns true if the deadline has passed without this `CondVar`
1065
  // being signalled in any manner. If both the deadline has passed
1066
  // and this `CondVar` has been signalled, the implementation is free
1067
  // to return `true` or `false`.
1068
  //
1069
  // Requires and ensures that the current thread holds the `Mutex`.
1070
0
  bool WaitWithDeadline(Mutex* absl_nonnull mu, absl::Time deadline) {
1071
0
    return WaitCommon(mu, synchronization_internal::KernelTimeout(deadline));
1072
0
  }
1073
1074
  // CondVar::Signal()
1075
  //
1076
  // Signal this `CondVar`; wake at least one waiter if one exists.
1077
  void Signal();
1078
1079
  // CondVar::SignalAll()
1080
  //
1081
  // Signal this `CondVar`; wake all waiters.
1082
  void SignalAll();
1083
1084
  // CondVar::EnableDebugLog()
1085
  //
1086
  // Causes all subsequent uses of this `CondVar` to be logged via
1087
  // `ABSL_RAW_LOG(INFO)`. Log entries are tagged with `name` if `name != 0`.
1088
  // Note: this method substantially reduces `CondVar` performance.
1089
  void EnableDebugLog(const char* absl_nullable name);
1090
1091
 private:
1092
  bool WaitCommon(Mutex* absl_nonnull mutex,
1093
                  synchronization_internal::KernelTimeout t);
1094
  void Remove(base_internal::PerThreadSynch* absl_nonnull s);
1095
  std::atomic<intptr_t> cv_;  // Condition variable state.
1096
  CondVar(const CondVar&) = delete;
1097
  CondVar& operator=(const CondVar&) = delete;
1098
};
1099
1100
// Variants of MutexLock.
1101
//
1102
// If you find yourself using one of these, consider instead using
1103
// Mutex::Unlock() and/or if-statements for clarity.
1104
1105
// MutexLockMaybe
1106
//
1107
// MutexLockMaybe is like MutexLock, but is a no-op when mu is null.
1108
class ABSL_SCOPED_LOCKABLE MutexLockMaybe {
1109
 public:
1110
  explicit MutexLockMaybe(Mutex* absl_nullable mu)
1111
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
1112
0
      : mu_(mu) {
1113
0
    if (this->mu_ != nullptr) {
1114
0
      this->mu_->lock();
1115
0
    }
1116
0
  }
1117
1118
  explicit MutexLockMaybe(Mutex* absl_nullable mu, const Condition& cond)
1119
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
1120
0
      : mu_(mu) {
1121
0
    if (this->mu_ != nullptr) {
1122
0
      this->mu_->LockWhen(cond);
1123
0
    }
1124
0
  }
1125
1126
0
  ~MutexLockMaybe() ABSL_UNLOCK_FUNCTION() {
1127
0
    if (this->mu_ != nullptr) {
1128
0
      this->mu_->unlock();
1129
0
    }
1130
0
  }
1131
1132
 private:
1133
  Mutex* absl_nullable const mu_;
1134
  MutexLockMaybe(const MutexLockMaybe&) = delete;
1135
  MutexLockMaybe(MutexLockMaybe&&) = delete;
1136
  MutexLockMaybe& operator=(const MutexLockMaybe&) = delete;
1137
  MutexLockMaybe& operator=(MutexLockMaybe&&) = delete;
1138
};
1139
1140
// ReleasableMutexLock
1141
//
1142
// ReleasableMutexLock is like MutexLock, but permits `Release()` of its
1143
// mutex before destruction. `Release()` may be called at most once.
1144
class ABSL_SCOPED_LOCKABLE ReleasableMutexLock {
1145
 public:
1146
  explicit ReleasableMutexLock(
1147
      Mutex& mu ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY_THIS)
1148
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
1149
0
      : mu_(&mu) {
1150
0
    this->mu_->lock();
1151
0
  }
1152
1153
  [[deprecated("Use the constructor that takes a reference instead")]]
1154
  ABSL_REFACTOR_INLINE
1155
  explicit ReleasableMutexLock(Mutex* absl_nonnull mu)
1156
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
1157
0
      : ReleasableMutexLock(*mu) {}
1158
1159
  explicit ReleasableMutexLock(
1160
      Mutex& mu ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY_THIS,
1161
      const Condition& cond) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
1162
0
      : mu_(&mu) {
1163
0
    this->mu_->LockWhen(cond);
1164
0
  }
1165
1166
  [[deprecated("Use the constructor that takes a reference instead")]]
1167
  ABSL_REFACTOR_INLINE
1168
  explicit ReleasableMutexLock(Mutex* absl_nonnull mu, const Condition& cond)
1169
      ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
1170
0
      : ReleasableMutexLock(*mu, cond) {}
1171
1172
0
  ~ReleasableMutexLock() ABSL_UNLOCK_FUNCTION() {
1173
0
    if (this->mu_ != nullptr) {
1174
0
      this->mu_->unlock();
1175
0
    }
1176
0
  }
1177
1178
  void Release() ABSL_UNLOCK_FUNCTION();
1179
1180
 private:
1181
  Mutex* absl_nullable mu_;
1182
  ReleasableMutexLock(const ReleasableMutexLock&) = delete;
1183
  ReleasableMutexLock(ReleasableMutexLock&&) = delete;
1184
  ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;
1185
  ReleasableMutexLock& operator=(ReleasableMutexLock&&) = delete;
1186
};
1187
1188
0
inline Mutex::Mutex() : mu_(0) {
1189
0
  ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
1190
0
}
1191
1192
constexpr Mutex::Mutex(absl::ConstInitType) : mu_(0) {}
1193
1194
#if !defined(__APPLE__) && !defined(ABSL_BUILD_DLL)
1195
ABSL_ATTRIBUTE_ALWAYS_INLINE
1196
0
inline Mutex::~Mutex() { Dtor(); }
1197
#endif
1198
1199
#if defined(NDEBUG) && !defined(ABSL_HAVE_THREAD_SANITIZER) && \
1200
    !defined(ABSL_BUILD_DLL)
1201
// Under NDEBUG and without TSAN, Dtor is normally fully inlined for
1202
// performance. However, when building Abseil as a shared library
1203
// (ABSL_BUILD_DLL), we must provide an out-of-line definition. This ensures the
1204
// Mutex::Dtor symbol is exported from the DLL, maintaining ABI compatibility
1205
// with clients that might be built in debug mode and thus expect the symbol.
1206
ABSL_ATTRIBUTE_ALWAYS_INLINE
1207
inline void Mutex::Dtor() {}
1208
#endif
1209
1210
inline CondVar::CondVar() : cv_(0) {}
1211
1212
// static
1213
template <typename T, typename ConditionMethodPtr>
1214
bool Condition::CastAndCallMethod(const Condition* absl_nonnull c) {
1215
  T* object = static_cast<T*>(c->arg_);
1216
  ConditionMethodPtr condition_method_pointer;
1217
  c->ReadCallback(&condition_method_pointer);
1218
  return (object->*condition_method_pointer)();
1219
}
1220
1221
// static
1222
template <typename T>
1223
0
bool Condition::CastAndCallFunction(const Condition* absl_nonnull c) {
1224
0
  bool (*function)(T*);
1225
0
  c->ReadCallback(&function);
1226
0
  T* argument = static_cast<T*>(c->arg_);
1227
0
  return (*function)(argument);
1228
0
}
1229
1230
template <typename T>
1231
inline Condition::Condition(
1232
    bool (*absl_nonnull func)(T* absl_nullability_unknown),
1233
    T* absl_nullability_unknown arg)
1234
0
    : eval_(&CastAndCallFunction<T>),
1235
0
      arg_(const_cast<void*>(static_cast<const void*>(arg))) {
1236
0
  static_assert(sizeof(&func) <= sizeof(callback_),
1237
0
                "An overlarge function pointer was passed to Condition.");
1238
0
  StoreCallback(func);
1239
0
}
1240
1241
template <typename T, typename>
1242
inline Condition::Condition(
1243
    bool (*absl_nonnull func)(T* absl_nullability_unknown),
1244
    typename absl::type_identity<T>::type* absl_nullability_unknown
1245
        arg)
1246
    // Just delegate to the overload above.
1247
    : Condition(func, arg) {}
1248
1249
template <typename T>
1250
inline Condition::Condition(
1251
    T* absl_nonnull object,
1252
    bool (absl::type_identity<T>::type::* absl_nonnull method)())
1253
    : eval_(&CastAndCallMethod<T, decltype(method)>), arg_(object) {
1254
  static_assert(sizeof(&method) <= sizeof(callback_),
1255
                "An overlarge method pointer was passed to Condition.");
1256
  StoreCallback(method);
1257
}
1258
1259
template <typename T>
1260
inline Condition::Condition(
1261
    const T* absl_nonnull object,
1262
    bool (absl::type_identity<T>::type::* absl_nonnull method)()
1263
        const)
1264
    : eval_(&CastAndCallMethod<const T, decltype(method)>),
1265
      arg_(reinterpret_cast<void*>(const_cast<T*>(object))) {
1266
  StoreCallback(method);
1267
}
1268
1269
// Register hooks for profiling support.
1270
//
1271
// The function pointer registered here will be called whenever a mutex is
1272
// contended.  The callback is given the cycles for which waiting happened (as
1273
// measured by //absl/base/internal/cycleclock.h, and which may not
1274
// be real "cycle" counts.)
1275
//
1276
// There is no ordering guarantee between when the hook is registered and when
1277
// callbacks will begin.  Only a single profiler can be installed in a running
1278
// binary; if this function is called a second time with a different function
1279
// pointer, the value is ignored (and will cause an assertion failure in debug
1280
// mode.)
1281
void RegisterMutexProfiler(void (*absl_nonnull fn)(int64_t wait_cycles));
1282
1283
// Register a hook for Mutex tracing.
1284
//
1285
// The function pointer registered here will be called whenever a mutex is
1286
// contended.  The callback is given an opaque handle to the contended mutex,
1287
// an event name, and the number of wait cycles (as measured by
1288
// //absl/base/internal/cycleclock.h, and which may not be real
1289
// "cycle" counts.)
1290
//
1291
// The only event name currently sent is "slow release".
1292
//
1293
// This has the same ordering and single-use limitations as
1294
// RegisterMutexProfiler() above.
1295
void RegisterMutexTracer(void (*absl_nonnull fn)(const char* absl_nonnull msg,
1296
                                                 const void* absl_nonnull obj,
1297
                                                 int64_t wait_cycles));
1298
1299
// Register a hook for CondVar tracing.
1300
//
1301
// The function pointer registered here will be called here on various CondVar
1302
// events.  The callback is given an opaque handle to the CondVar object and
1303
// a string identifying the event.  This is thread-safe, but only a single
1304
// tracer can be registered.
1305
//
1306
// Events that can be sent are "Wait", "Unwait", "Signal wakeup", and
1307
// "SignalAll wakeup".
1308
//
1309
// This has the same ordering and single-use limitations as
1310
// RegisterMutexProfiler() above.
1311
void RegisterCondVarTracer(void (*absl_nonnull fn)(
1312
    const char* absl_nonnull msg, const void* absl_nonnull cv));
1313
1314
// EnableMutexInvariantDebugging()
1315
//
1316
// Enable or disable global support for Mutex invariant debugging.  If enabled,
1317
// then invariant predicates can be registered per-Mutex for debug checking.
1318
// See Mutex::EnableInvariantDebugging().
1319
void EnableMutexInvariantDebugging(bool enabled);
1320
1321
// When in debug mode, and when the feature has been enabled globally, the
1322
// implementation will keep track of lock ordering and complain (or optionally
1323
// crash) if a cycle is detected in the acquired-before graph.
1324
1325
// Possible modes of operation for the deadlock detector in debug mode.
1326
enum class OnDeadlockCycle {
1327
  kIgnore,  // Neither report on nor attempt to track cycles in lock ordering
1328
  kReport,  // Report lock cycles to stderr when detected
1329
  kAbort,   // Report lock cycles to stderr when detected, then abort
1330
};
1331
1332
// SetMutexDeadlockDetectionMode()
1333
//
1334
// Enable or disable global support for detection of potential deadlocks
1335
// due to Mutex lock ordering inversions.  When set to 'kIgnore', tracking of
1336
// lock ordering is disabled.  Otherwise, in debug builds, a lock ordering graph
1337
// will be maintained internally, and detected cycles will be reported in
1338
// the manner chosen here.
1339
void SetMutexDeadlockDetectionMode(OnDeadlockCycle mode);
1340
1341
ABSL_NAMESPACE_END
1342
}  // namespace absl
1343
1344
// In some build configurations we pass --detect-odr-violations to the
1345
// gold linker.  This causes it to flag weak symbol overrides as ODR
1346
// violations.  Because ODR only applies to C++ and not C,
1347
// --detect-odr-violations ignores symbols not mangled with C++ names.
1348
// By changing our extension points to be extern "C", we dodge this
1349
// check.
1350
extern "C" {
1351
void ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)();
1352
}  // extern "C"
1353
1354
#endif  // ABSL_SYNCHRONIZATION_MUTEX_H_