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