00001 // Copyright 2017 The Abseil Authors. 00002 // 00003 // Licensed under the Apache License, Version 2.0 (the "License"); 00004 // you may not use this file except in compliance with the License. 00005 // You may obtain a copy of the License at 00006 // 00007 // https://www.apache.org/licenses/LICENSE-2.0 00008 // 00009 // Unless required by applicable law or agreed to in writing, software 00010 // distributed under the License is distributed on an "AS IS" BASIS, 00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00012 // See the License for the specific language governing permissions and 00013 // limitations under the License. 00014 // 00015 // ----------------------------------------------------------------------------- 00016 // mutex.h 00017 // ----------------------------------------------------------------------------- 00018 // 00019 // This header file defines a `Mutex` -- a mutually exclusive lock -- and the 00020 // most common type of synchronization primitive for facilitating locks on 00021 // shared resources. A mutex is used to prevent multiple threads from accessing 00022 // and/or writing to a shared resource concurrently. 00023 // 00024 // Unlike a `std::mutex`, the Abseil `Mutex` provides the following additional 00025 // features: 00026 // * Conditional predicates intrinsic to the `Mutex` object 00027 // * Shared/reader locks, in addition to standard exclusive/writer locks 00028 // * Deadlock detection and debug support. 00029 // 00030 // The following helper classes are also defined within this file: 00031 // 00032 // MutexLock - An RAII wrapper to acquire and release a `Mutex` for exclusive/ 00033 // write access within the current scope. 00034 // ReaderMutexLock 00035 // - An RAII wrapper to acquire and release a `Mutex` for shared/read 00036 // access within the current scope. 00037 // 00038 // WriterMutexLock 00039 // - Alias for `MutexLock` above, designed for use in distinguishing 00040 // reader and writer locks within code. 00041 // 00042 // In addition to simple mutex locks, this file also defines ways to perform 00043 // locking under certain conditions. 00044 // 00045 // Condition - (Preferred) Used to wait for a particular predicate that 00046 // depends on state protected by the `Mutex` to become true. 00047 // CondVar - A lower-level variant of `Condition` that relies on 00048 // application code to explicitly signal the `CondVar` when 00049 // a condition has been met. 00050 // 00051 // See below for more information on using `Condition` or `CondVar`. 00052 // 00053 // Mutexes and mutex behavior can be quite complicated. The information within 00054 // this header file is limited, as a result. Please consult the Mutex guide for 00055 // more complete information and examples. 00056 00057 #ifndef ABSL_SYNCHRONIZATION_MUTEX_H_ 00058 #define ABSL_SYNCHRONIZATION_MUTEX_H_ 00059 00060 #include <atomic> 00061 #include <cstdint> 00062 #include <string> 00063 00064 #include "absl/base/const_init.h" 00065 #include "absl/base/internal/identity.h" 00066 #include "absl/base/internal/low_level_alloc.h" 00067 #include "absl/base/internal/thread_identity.h" 00068 #include "absl/base/internal/tsan_mutex_interface.h" 00069 #include "absl/base/port.h" 00070 #include "absl/base/thread_annotations.h" 00071 #include "absl/synchronization/internal/kernel_timeout.h" 00072 #include "absl/synchronization/internal/per_thread_sem.h" 00073 #include "absl/time/time.h" 00074 00075 // Decide if we should use the non-production implementation because 00076 // the production implementation hasn't been fully ported yet. 00077 #ifdef ABSL_INTERNAL_USE_NONPROD_MUTEX 00078 #error ABSL_INTERNAL_USE_NONPROD_MUTEX cannot be directly set 00079 #elif defined(ABSL_LOW_LEVEL_ALLOC_MISSING) 00080 #define ABSL_INTERNAL_USE_NONPROD_MUTEX 1 00081 #include "absl/synchronization/internal/mutex_nonprod.inc" 00082 #endif 00083 00084 namespace absl { 00085 00086 class Condition; 00087 struct SynchWaitParams; 00088 00089 // ----------------------------------------------------------------------------- 00090 // Mutex 00091 // ----------------------------------------------------------------------------- 00092 // 00093 // A `Mutex` is a non-reentrant (aka non-recursive) Mutually Exclusive lock 00094 // on some resource, typically a variable or data structure with associated 00095 // invariants. Proper usage of mutexes prevents concurrent access by different 00096 // threads to the same resource. 00097 // 00098 // A `Mutex` has two basic operations: `Mutex::Lock()` and `Mutex::Unlock()`. 00099 // The `Lock()` operation *acquires* a `Mutex` (in a state known as an 00100 // *exclusive* -- or write -- lock), while the `Unlock()` operation *releases* a 00101 // Mutex. During the span of time between the Lock() and Unlock() operations, 00102 // a mutex is said to be *held*. By design all mutexes support exclusive/write 00103 // locks, as this is the most common way to use a mutex. 00104 // 00105 // The `Mutex` state machine for basic lock/unlock operations is quite simple: 00106 // 00107 // | | Lock() | Unlock() | 00108 // |----------------+------------+----------| 00109 // | Free | Exclusive | invalid | 00110 // | Exclusive | blocks | Free | 00111 // 00112 // Attempts to `Unlock()` must originate from the thread that performed the 00113 // corresponding `Lock()` operation. 00114 // 00115 // An "invalid" operation is disallowed by the API. The `Mutex` implementation 00116 // is allowed to do anything on an invalid call, including but not limited to 00117 // crashing with a useful error message, silently succeeding, or corrupting 00118 // data structures. In debug mode, the implementation attempts to crash with a 00119 // useful error message. 00120 // 00121 // `Mutex` is not guaranteed to be "fair" in prioritizing waiting threads; it 00122 // is, however, approximately fair over long periods, and starvation-free for 00123 // threads at the same priority. 00124 // 00125 // The lock/unlock primitives are now annotated with lock annotations 00126 // defined in (base/thread_annotations.h). When writing multi-threaded code, 00127 // you should use lock annotations whenever possible to document your lock 00128 // synchronization policy. Besides acting as documentation, these annotations 00129 // also help compilers or static analysis tools to identify and warn about 00130 // issues that could potentially result in race conditions and deadlocks. 00131 // 00132 // For more information about the lock annotations, please see 00133 // [Thread Safety Analysis](http://clang.llvm.org/docs/ThreadSafetyAnalysis.html) 00134 // in the Clang documentation. 00135 // 00136 // See also `MutexLock`, below, for scoped `Mutex` acquisition. 00137 00138 class LOCKABLE Mutex { 00139 public: 00140 // Creates a `Mutex` that is not held by anyone. This constructor is 00141 // typically used for Mutexes allocated on the heap or the stack. 00142 // 00143 // To create `Mutex` instances with static storage duration 00144 // (e.g. a namespace-scoped or global variable), see 00145 // `Mutex::Mutex(absl::kConstInit)` below instead. 00146 Mutex(); 00147 00148 // Creates a mutex with static storage duration. A global variable 00149 // constructed this way avoids the lifetime issues that can occur on program 00150 // startup and shutdown. (See absl/base/const_init.h.) 00151 // 00152 // For Mutexes allocated on the heap and stack, instead use the default 00153 // constructor, which can interact more fully with the thread sanitizer. 00154 // 00155 // Example usage: 00156 // namespace foo { 00157 // ABSL_CONST_INIT Mutex mu(absl::kConstInit); 00158 // } 00159 explicit constexpr Mutex(absl::ConstInitType); 00160 00161 ~Mutex(); 00162 00163 // Mutex::Lock() 00164 // 00165 // Blocks the calling thread, if necessary, until this `Mutex` is free, and 00166 // then acquires it exclusively. (This lock is also known as a "write lock.") 00167 void Lock() EXCLUSIVE_LOCK_FUNCTION(); 00168 00169 // Mutex::Unlock() 00170 // 00171 // Releases this `Mutex` and returns it from the exclusive/write state to the 00172 // free state. Caller must hold the `Mutex` exclusively. 00173 void Unlock() UNLOCK_FUNCTION(); 00174 00175 // Mutex::TryLock() 00176 // 00177 // If the mutex can be acquired without blocking, does so exclusively and 00178 // returns `true`. Otherwise, returns `false`. Returns `true` with high 00179 // probability if the `Mutex` was free. 00180 bool TryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true); 00181 00182 // Mutex::AssertHeld() 00183 // 00184 // Return immediately if this thread holds the `Mutex` exclusively (in write 00185 // mode). Otherwise, may report an error (typically by crashing with a 00186 // diagnostic), or may return immediately. 00187 void AssertHeld() const ASSERT_EXCLUSIVE_LOCK(); 00188 00189 // --------------------------------------------------------------------------- 00190 // Reader-Writer Locking 00191 // --------------------------------------------------------------------------- 00192 00193 // A Mutex can also be used as a starvation-free reader-writer lock. 00194 // Neither read-locks nor write-locks are reentrant/recursive to avoid 00195 // potential client programming errors. 00196 // 00197 // The Mutex API provides `Writer*()` aliases for the existing `Lock()`, 00198 // `Unlock()` and `TryLock()` methods for use within applications mixing 00199 // reader/writer locks. Using `Reader*()` and `Writer*()` operations in this 00200 // manner can make locking behavior clearer when mixing read and write modes. 00201 // 00202 // Introducing reader locks necessarily complicates the `Mutex` state 00203 // machine somewhat. The table below illustrates the allowed state transitions 00204 // of a mutex in such cases. Note that ReaderLock() may block even if the lock 00205 // is held in shared mode; this occurs when another thread is blocked on a 00206 // call to WriterLock(). 00207 // 00208 // --------------------------------------------------------------------------- 00209 // Operation: WriterLock() Unlock() ReaderLock() ReaderUnlock() 00210 // --------------------------------------------------------------------------- 00211 // State 00212 // --------------------------------------------------------------------------- 00213 // Free Exclusive invalid Shared(1) invalid 00214 // Shared(1) blocks invalid Shared(2) or blocks Free 00215 // Shared(n) n>1 blocks invalid Shared(n+1) or blocks Shared(n-1) 00216 // Exclusive blocks Free blocks invalid 00217 // --------------------------------------------------------------------------- 00218 // 00219 // In comments below, "shared" refers to a state of Shared(n) for any n > 0. 00220 00221 // Mutex::ReaderLock() 00222 // 00223 // Blocks the calling thread, if necessary, until this `Mutex` is either free, 00224 // or in shared mode, and then acquires a share of it. Note that 00225 // `ReaderLock()` will block if some other thread has an exclusive/writer lock 00226 // on the mutex. 00227 00228 void ReaderLock() SHARED_LOCK_FUNCTION(); 00229 00230 // Mutex::ReaderUnlock() 00231 // 00232 // Releases a read share of this `Mutex`. `ReaderUnlock` may return a mutex to 00233 // the free state if this thread holds the last reader lock on the mutex. Note 00234 // that you cannot call `ReaderUnlock()` on a mutex held in write mode. 00235 void ReaderUnlock() UNLOCK_FUNCTION(); 00236 00237 // Mutex::ReaderTryLock() 00238 // 00239 // If the mutex can be acquired without blocking, acquires this mutex for 00240 // shared access and returns `true`. Otherwise, returns `false`. Returns 00241 // `true` with high probability if the `Mutex` was free or shared. 00242 bool ReaderTryLock() SHARED_TRYLOCK_FUNCTION(true); 00243 00244 // Mutex::AssertReaderHeld() 00245 // 00246 // Returns immediately if this thread holds the `Mutex` in at least shared 00247 // mode (read mode). Otherwise, may report an error (typically by 00248 // crashing with a diagnostic), or may return immediately. 00249 void AssertReaderHeld() const ASSERT_SHARED_LOCK(); 00250 00251 // Mutex::WriterLock() 00252 // Mutex::WriterUnlock() 00253 // Mutex::WriterTryLock() 00254 // 00255 // Aliases for `Mutex::Lock()`, `Mutex::Unlock()`, and `Mutex::TryLock()`. 00256 // 00257 // These methods may be used (along with the complementary `Reader*()` 00258 // methods) to distingish simple exclusive `Mutex` usage (`Lock()`, 00259 // etc.) from reader/writer lock usage. 00260 void WriterLock() EXCLUSIVE_LOCK_FUNCTION() { this->Lock(); } 00261 00262 void WriterUnlock() UNLOCK_FUNCTION() { this->Unlock(); } 00263 00264 bool WriterTryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true) { 00265 return this->TryLock(); 00266 } 00267 00268 // --------------------------------------------------------------------------- 00269 // Conditional Critical Regions 00270 // --------------------------------------------------------------------------- 00271 00272 // Conditional usage of a `Mutex` can occur using two distinct paradigms: 00273 // 00274 // * Use of `Mutex` member functions with `Condition` objects. 00275 // * Use of the separate `CondVar` abstraction. 00276 // 00277 // In general, prefer use of `Condition` and the `Mutex` member functions 00278 // listed below over `CondVar`. When there are multiple threads waiting on 00279 // distinctly different conditions, however, a battery of `CondVar`s may be 00280 // more efficient. This section discusses use of `Condition` objects. 00281 // 00282 // `Mutex` contains member functions for performing lock operations only under 00283 // certain conditions, of class `Condition`. For correctness, the `Condition` 00284 // must return a boolean that is a pure function, only of state protected by 00285 // the `Mutex`. The condition must be invariant w.r.t. environmental state 00286 // such as thread, cpu id, or time, and must be `noexcept`. The condition will 00287 // always be invoked with the mutex held in at least read mode, so you should 00288 // not block it for long periods or sleep it on a timer. 00289 // 00290 // Since a condition must not depend directly on the current time, use 00291 // `*WithTimeout()` member function variants to make your condition 00292 // effectively true after a given duration, or `*WithDeadline()` variants to 00293 // make your condition effectively true after a given time. 00294 // 00295 // The condition function should have no side-effects aside from debug 00296 // logging; as a special exception, the function may acquire other mutexes 00297 // provided it releases all those that it acquires. (This exception was 00298 // required to allow logging.) 00299 00300 // Mutex::Await() 00301 // 00302 // Unlocks this `Mutex` and blocks until simultaneously both `cond` is `true` 00303 // and this `Mutex` can be reacquired, then reacquires this `Mutex` in the 00304 // same mode in which it was previously held. If the condition is initially 00305 // `true`, `Await()` *may* skip the release/re-acquire step. 00306 // 00307 // `Await()` requires that this thread holds this `Mutex` in some mode. 00308 void Await(const Condition &cond); 00309 00310 // Mutex::LockWhen() 00311 // Mutex::ReaderLockWhen() 00312 // Mutex::WriterLockWhen() 00313 // 00314 // Blocks until simultaneously both `cond` is `true` and this `Mutex` can 00315 // be acquired, then atomically acquires this `Mutex`. `LockWhen()` is 00316 // logically equivalent to `*Lock(); Await();` though they may have different 00317 // performance characteristics. 00318 void LockWhen(const Condition &cond) EXCLUSIVE_LOCK_FUNCTION(); 00319 00320 void ReaderLockWhen(const Condition &cond) SHARED_LOCK_FUNCTION(); 00321 00322 void WriterLockWhen(const Condition &cond) EXCLUSIVE_LOCK_FUNCTION() { 00323 this->LockWhen(cond); 00324 } 00325 00326 // --------------------------------------------------------------------------- 00327 // Mutex Variants with Timeouts/Deadlines 00328 // --------------------------------------------------------------------------- 00329 00330 // Mutex::AwaitWithTimeout() 00331 // Mutex::AwaitWithDeadline() 00332 // 00333 // If `cond` is initially true, do nothing, or act as though `cond` is 00334 // initially false. 00335 // 00336 // If `cond` is initially false, unlock this `Mutex` and block until 00337 // simultaneously: 00338 // - either `cond` is true or the {timeout has expired, deadline has passed} 00339 // and 00340 // - this `Mutex` can be reacquired, 00341 // then reacquire this `Mutex` in the same mode in which it was previously 00342 // held, returning `true` iff `cond` is `true` on return. 00343 // 00344 // Deadlines in the past are equivalent to an immediate deadline. 00345 // Negative timeouts are equivalent to a zero timeout. 00346 // 00347 // This method requires that this thread holds this `Mutex` in some mode. 00348 bool AwaitWithTimeout(const Condition &cond, absl::Duration timeout); 00349 00350 bool AwaitWithDeadline(const Condition &cond, absl::Time deadline); 00351 00352 // Mutex::LockWhenWithTimeout() 00353 // Mutex::ReaderLockWhenWithTimeout() 00354 // Mutex::WriterLockWhenWithTimeout() 00355 // 00356 // Blocks until simultaneously both: 00357 // - either `cond` is `true` or the timeout has expired, and 00358 // - this `Mutex` can be acquired, 00359 // then atomically acquires this `Mutex`, returning `true` iff `cond` is 00360 // `true` on return. 00361 // 00362 // Negative timeouts are equivalent to a zero timeout. 00363 bool LockWhenWithTimeout(const Condition &cond, absl::Duration timeout) 00364 EXCLUSIVE_LOCK_FUNCTION(); 00365 bool ReaderLockWhenWithTimeout(const Condition &cond, absl::Duration timeout) 00366 SHARED_LOCK_FUNCTION(); 00367 bool WriterLockWhenWithTimeout(const Condition &cond, absl::Duration timeout) 00368 EXCLUSIVE_LOCK_FUNCTION() { 00369 return this->LockWhenWithTimeout(cond, timeout); 00370 } 00371 00372 // Mutex::LockWhenWithDeadline() 00373 // Mutex::ReaderLockWhenWithDeadline() 00374 // Mutex::WriterLockWhenWithDeadline() 00375 // 00376 // Blocks until simultaneously both: 00377 // - either `cond` is `true` or the deadline has been passed, and 00378 // - this `Mutex` can be acquired, 00379 // then atomically acquires this Mutex, returning `true` iff `cond` is `true` 00380 // on return. 00381 // 00382 // Deadlines in the past are equivalent to an immediate deadline. 00383 bool LockWhenWithDeadline(const Condition &cond, absl::Time deadline) 00384 EXCLUSIVE_LOCK_FUNCTION(); 00385 bool ReaderLockWhenWithDeadline(const Condition &cond, absl::Time deadline) 00386 SHARED_LOCK_FUNCTION(); 00387 bool WriterLockWhenWithDeadline(const Condition &cond, absl::Time deadline) 00388 EXCLUSIVE_LOCK_FUNCTION() { 00389 return this->LockWhenWithDeadline(cond, deadline); 00390 } 00391 00392 // --------------------------------------------------------------------------- 00393 // Debug Support: Invariant Checking, Deadlock Detection, Logging. 00394 // --------------------------------------------------------------------------- 00395 00396 // Mutex::EnableInvariantDebugging() 00397 // 00398 // If `invariant`!=null and if invariant debugging has been enabled globally, 00399 // cause `(*invariant)(arg)` to be called at moments when the invariant for 00400 // this `Mutex` should hold (for example: just after acquire, just before 00401 // release). 00402 // 00403 // The routine `invariant` should have no side-effects since it is not 00404 // guaranteed how many times it will be called; it should check the invariant 00405 // and crash if it does not hold. Enabling global invariant debugging may 00406 // substantially reduce `Mutex` performance; it should be set only for 00407 // non-production runs. Optimization options may also disable invariant 00408 // checks. 00409 void EnableInvariantDebugging(void (*invariant)(void *), void *arg); 00410 00411 // Mutex::EnableDebugLog() 00412 // 00413 // Cause all subsequent uses of this `Mutex` to be logged via 00414 // `ABSL_RAW_LOG(INFO)`. Log entries are tagged with `name` if no previous 00415 // call to `EnableInvariantDebugging()` or `EnableDebugLog()` has been made. 00416 // 00417 // Note: This method substantially reduces `Mutex` performance. 00418 void EnableDebugLog(const char *name); 00419 00420 // Deadlock detection 00421 00422 // Mutex::ForgetDeadlockInfo() 00423 // 00424 // Forget any deadlock-detection information previously gathered 00425 // about this `Mutex`. Call this method in debug mode when the lock ordering 00426 // of a `Mutex` changes. 00427 void ForgetDeadlockInfo(); 00428 00429 // Mutex::AssertNotHeld() 00430 // 00431 // Return immediately if this thread does not hold this `Mutex` in any 00432 // mode; otherwise, may report an error (typically by crashing with a 00433 // diagnostic), or may return immediately. 00434 // 00435 // Currently this check is performed only if all of: 00436 // - in debug mode 00437 // - SetMutexDeadlockDetectionMode() has been set to kReport or kAbort 00438 // - number of locks concurrently held by this thread is not large. 00439 // are true. 00440 void AssertNotHeld() const; 00441 00442 // Special cases. 00443 00444 // A `MuHow` is a constant that indicates how a lock should be acquired. 00445 // Internal implementation detail. Clients should ignore. 00446 typedef const struct MuHowS *MuHow; 00447 00448 // Mutex::InternalAttemptToUseMutexInFatalSignalHandler() 00449 // 00450 // Causes the `Mutex` implementation to prepare itself for re-entry caused by 00451 // future use of `Mutex` within a fatal signal handler. This method is 00452 // intended for use only for last-ditch attempts to log crash information. 00453 // It does not guarantee that attempts to use Mutexes within the handler will 00454 // not deadlock; it merely makes other faults less likely. 00455 // 00456 // WARNING: This routine must be invoked from a signal handler, and the 00457 // signal handler must either loop forever or terminate the process. 00458 // Attempts to return from (or `longjmp` out of) the signal handler once this 00459 // call has been made may cause arbitrary program behaviour including 00460 // crashes and deadlocks. 00461 static void InternalAttemptToUseMutexInFatalSignalHandler(); 00462 00463 private: 00464 #ifdef ABSL_INTERNAL_USE_NONPROD_MUTEX 00465 friend class CondVar; 00466 00467 synchronization_internal::MutexImpl *impl() { return impl_.get(); } 00468 00469 synchronization_internal::SynchronizationStorage< 00470 synchronization_internal::MutexImpl> 00471 impl_; 00472 #else 00473 std::atomic<intptr_t> mu_; // The Mutex state. 00474 00475 // Post()/Wait() versus associated PerThreadSem; in class for required 00476 // friendship with PerThreadSem. 00477 static inline void IncrementSynchSem(Mutex *mu, 00478 base_internal::PerThreadSynch *w); 00479 static inline bool DecrementSynchSem( 00480 Mutex *mu, base_internal::PerThreadSynch *w, 00481 synchronization_internal::KernelTimeout t); 00482 00483 // slow path acquire 00484 void LockSlowLoop(SynchWaitParams *waitp, int flags); 00485 // wrappers around LockSlowLoop() 00486 bool LockSlowWithDeadline(MuHow how, const Condition *cond, 00487 synchronization_internal::KernelTimeout t, 00488 int flags); 00489 void LockSlow(MuHow how, const Condition *cond, 00490 int flags) ABSL_ATTRIBUTE_COLD; 00491 // slow path release 00492 void UnlockSlow(SynchWaitParams *waitp) ABSL_ATTRIBUTE_COLD; 00493 // Common code between Await() and AwaitWithTimeout/Deadline() 00494 bool AwaitCommon(const Condition &cond, 00495 synchronization_internal::KernelTimeout t); 00496 // Attempt to remove thread s from queue. 00497 void TryRemove(base_internal::PerThreadSynch *s); 00498 // Block a thread on mutex. 00499 void Block(base_internal::PerThreadSynch *s); 00500 // Wake a thread; return successor. 00501 base_internal::PerThreadSynch *Wakeup(base_internal::PerThreadSynch *w); 00502 00503 friend class CondVar; // for access to Trans()/Fer(). 00504 void Trans(MuHow how); // used for CondVar->Mutex transfer 00505 void Fer( 00506 base_internal::PerThreadSynch *w); // used for CondVar->Mutex transfer 00507 #endif 00508 00509 // Catch the error of writing Mutex when intending MutexLock. 00510 Mutex(const volatile Mutex * /*ignored*/) {} // NOLINT(runtime/explicit) 00511 00512 Mutex(const Mutex&) = delete; 00513 Mutex& operator=(const Mutex&) = delete; 00514 }; 00515 00516 // ----------------------------------------------------------------------------- 00517 // Mutex RAII Wrappers 00518 // ----------------------------------------------------------------------------- 00519 00520 // MutexLock 00521 // 00522 // `MutexLock` is a helper class, which acquires and releases a `Mutex` via 00523 // RAII. 00524 // 00525 // Example: 00526 // 00527 // Class Foo { 00528 // 00529 // Foo::Bar* Baz() { 00530 // MutexLock l(&lock_); 00531 // ... 00532 // return bar; 00533 // } 00534 // 00535 // private: 00536 // Mutex lock_; 00537 // }; 00538 class SCOPED_LOCKABLE MutexLock { 00539 public: 00540 explicit MutexLock(Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) { 00541 this->mu_->Lock(); 00542 } 00543 00544 MutexLock(const MutexLock &) = delete; // NOLINT(runtime/mutex) 00545 MutexLock(MutexLock&&) = delete; // NOLINT(runtime/mutex) 00546 MutexLock& operator=(const MutexLock&) = delete; 00547 MutexLock& operator=(MutexLock&&) = delete; 00548 00549 ~MutexLock() UNLOCK_FUNCTION() { this->mu_->Unlock(); } 00550 00551 private: 00552 Mutex *const mu_; 00553 }; 00554 00555 // ReaderMutexLock 00556 // 00557 // The `ReaderMutexLock` is a helper class, like `MutexLock`, which acquires and 00558 // releases a shared lock on a `Mutex` via RAII. 00559 class SCOPED_LOCKABLE ReaderMutexLock { 00560 public: 00561 explicit ReaderMutexLock(Mutex *mu) SHARED_LOCK_FUNCTION(mu) 00562 : mu_(mu) { 00563 mu->ReaderLock(); 00564 } 00565 00566 ReaderMutexLock(const ReaderMutexLock&) = delete; 00567 ReaderMutexLock(ReaderMutexLock&&) = delete; 00568 ReaderMutexLock& operator=(const ReaderMutexLock&) = delete; 00569 ReaderMutexLock& operator=(ReaderMutexLock&&) = delete; 00570 00571 ~ReaderMutexLock() UNLOCK_FUNCTION() { 00572 this->mu_->ReaderUnlock(); 00573 } 00574 00575 private: 00576 Mutex *const mu_; 00577 }; 00578 00579 // WriterMutexLock 00580 // 00581 // The `WriterMutexLock` is a helper class, like `MutexLock`, which acquires and 00582 // releases a write (exclusive) lock on a `Mutex` via RAII. 00583 class SCOPED_LOCKABLE WriterMutexLock { 00584 public: 00585 explicit WriterMutexLock(Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) 00586 : mu_(mu) { 00587 mu->WriterLock(); 00588 } 00589 00590 WriterMutexLock(const WriterMutexLock&) = delete; 00591 WriterMutexLock(WriterMutexLock&&) = delete; 00592 WriterMutexLock& operator=(const WriterMutexLock&) = delete; 00593 WriterMutexLock& operator=(WriterMutexLock&&) = delete; 00594 00595 ~WriterMutexLock() UNLOCK_FUNCTION() { 00596 this->mu_->WriterUnlock(); 00597 } 00598 00599 private: 00600 Mutex *const mu_; 00601 }; 00602 00603 // ----------------------------------------------------------------------------- 00604 // Condition 00605 // ----------------------------------------------------------------------------- 00606 // 00607 // As noted above, `Mutex` contains a number of member functions which take a 00608 // `Condition` as an argument; clients can wait for conditions to become `true` 00609 // before attempting to acquire the mutex. These sections are known as 00610 // "condition critical" sections. To use a `Condition`, you simply need to 00611 // construct it, and use within an appropriate `Mutex` member function; 00612 // everything else in the `Condition` class is an implementation detail. 00613 // 00614 // A `Condition` is specified as a function pointer which returns a boolean. 00615 // `Condition` functions should be pure functions -- their results should depend 00616 // only on passed arguments, should not consult any external state (such as 00617 // clocks), and should have no side-effects, aside from debug logging. Any 00618 // objects that the function may access should be limited to those which are 00619 // constant while the mutex is blocked on the condition (e.g. a stack variable), 00620 // or objects of state protected explicitly by the mutex. 00621 // 00622 // No matter which construction is used for `Condition`, the underlying 00623 // function pointer / functor / callable must not throw any 00624 // exceptions. Correctness of `Mutex` / `Condition` is not guaranteed in 00625 // the face of a throwing `Condition`. (When Abseil is allowed to depend 00626 // on C++17, these function pointers will be explicitly marked 00627 // `noexcept`; until then this requirement cannot be enforced in the 00628 // type system.) 00629 // 00630 // Note: to use a `Condition`, you need only construct it and pass it within the 00631 // appropriate `Mutex' member function, such as `Mutex::Await()`. 00632 // 00633 // Example: 00634 // 00635 // // assume count_ is not internal reference count 00636 // int count_ GUARDED_BY(mu_); 00637 // 00638 // mu_.LockWhen(Condition(+[](int* count) { return *count == 0; }, 00639 // &count_)); 00640 // 00641 // When multiple threads are waiting on exactly the same condition, make sure 00642 // that they are constructed with the same parameters (same pointer to function 00643 // + arg, or same pointer to object + method), so that the mutex implementation 00644 // can avoid redundantly evaluating the same condition for each thread. 00645 class Condition { 00646 public: 00647 // A Condition that returns the result of "(*func)(arg)" 00648 Condition(bool (*func)(void *), void *arg); 00649 00650 // Templated version for people who are averse to casts. 00651 // 00652 // To use a lambda, prepend it with unary plus, which converts the lambda 00653 // into a function pointer: 00654 // Condition(+[](T* t) { return ...; }, arg). 00655 // 00656 // Note: lambdas in this case must contain no bound variables. 00657 // 00658 // See class comment for performance advice. 00659 template<typename T> 00660 Condition(bool (*func)(T *), T *arg); 00661 00662 // Templated version for invoking a method that returns a `bool`. 00663 // 00664 // `Condition(object, &Class::Method)` constructs a `Condition` that evaluates 00665 // `object->Method()`. 00666 // 00667 // Implementation Note: `absl::internal::identity` is used to allow methods to 00668 // come from base classes. A simpler signature like 00669 // `Condition(T*, bool (T::*)())` does not suffice. 00670 template<typename T> 00671 Condition(T *object, bool (absl::internal::identity<T>::type::* method)()); 00672 00673 // Same as above, for const members 00674 template<typename T> 00675 Condition(const T *object, 00676 bool (absl::internal::identity<T>::type::* method)() const); 00677 00678 // A Condition that returns the value of `*cond` 00679 explicit Condition(const bool *cond); 00680 00681 // Templated version for invoking a functor that returns a `bool`. 00682 // This approach accepts pointers to non-mutable lambdas, `std::function`, 00683 // the result of` std::bind` and user-defined functors that define 00684 // `bool F::operator()() const`. 00685 // 00686 // Example: 00687 // 00688 // auto reached = [this, current]() { 00689 // mu_.AssertReaderHeld(); // For annotalysis. 00690 // return processed_ >= current; 00691 // }; 00692 // mu_.Await(Condition(&reached)); 00693 00694 // See class comment for performance advice. In particular, if there 00695 // might be more than one waiter for the same condition, make sure 00696 // that all waiters construct the condition with the same pointers. 00697 00698 // Implementation note: The second template parameter ensures that this 00699 // constructor doesn't participate in overload resolution if T doesn't have 00700 // `bool operator() const`. 00701 template <typename T, typename E = decltype( 00702 static_cast<bool (T::*)() const>(&T::operator()))> 00703 explicit Condition(const T *obj) 00704 : Condition(obj, static_cast<bool (T::*)() const>(&T::operator())) {} 00705 00706 // A Condition that always returns `true`. 00707 static const Condition kTrue; 00708 00709 // Evaluates the condition. 00710 bool Eval() const; 00711 00712 // Returns `true` if the two conditions are guaranteed to return the same 00713 // value if evaluated at the same time, `false` if the evaluation *may* return 00714 // different results. 00715 // 00716 // Two `Condition` values are guaranteed equal if both their `func` and `arg` 00717 // components are the same. A null pointer is equivalent to a `true` 00718 // condition. 00719 static bool GuaranteedEqual(const Condition *a, const Condition *b); 00720 00721 private: 00722 typedef bool (*InternalFunctionType)(void * arg); 00723 typedef bool (Condition::*InternalMethodType)(); 00724 typedef bool (*InternalMethodCallerType)(void * arg, 00725 InternalMethodType internal_method); 00726 00727 bool (*eval_)(const Condition*); // Actual evaluator 00728 InternalFunctionType function_; // function taking pointer returning bool 00729 InternalMethodType method_; // method returning bool 00730 void *arg_; // arg of function_ or object of method_ 00731 00732 Condition(); // null constructor used only to create kTrue 00733 00734 // Various functions eval_ can point to: 00735 static bool CallVoidPtrFunction(const Condition*); 00736 template <typename T> static bool CastAndCallFunction(const Condition* c); 00737 template <typename T> static bool CastAndCallMethod(const Condition* c); 00738 }; 00739 00740 // ----------------------------------------------------------------------------- 00741 // CondVar 00742 // ----------------------------------------------------------------------------- 00743 // 00744 // A condition variable, reflecting state evaluated separately outside of the 00745 // `Mutex` object, which can be signaled to wake callers. 00746 // This class is not normally needed; use `Mutex` member functions such as 00747 // `Mutex::Await()` and intrinsic `Condition` abstractions. In rare cases 00748 // with many threads and many conditions, `CondVar` may be faster. 00749 // 00750 // The implementation may deliver signals to any condition variable at 00751 // any time, even when no call to `Signal()` or `SignalAll()` is made; as a 00752 // result, upon being awoken, you must check the logical condition you have 00753 // been waiting upon. 00754 // 00755 // Examples: 00756 // 00757 // Usage for a thread waiting for some condition C protected by mutex mu: 00758 // mu.Lock(); 00759 // while (!C) { cv->Wait(&mu); } // releases and reacquires mu 00760 // // C holds; process data 00761 // mu.Unlock(); 00762 // 00763 // Usage to wake T is: 00764 // mu.Lock(); 00765 // // process data, possibly establishing C 00766 // if (C) { cv->Signal(); } 00767 // mu.Unlock(); 00768 // 00769 // If C may be useful to more than one waiter, use `SignalAll()` instead of 00770 // `Signal()`. 00771 // 00772 // With this implementation it is efficient to use `Signal()/SignalAll()` inside 00773 // the locked region; this usage can make reasoning about your program easier. 00774 // 00775 class CondVar { 00776 public: 00777 CondVar(); 00778 ~CondVar(); 00779 00780 // CondVar::Wait() 00781 // 00782 // Atomically releases a `Mutex` and blocks on this condition variable. 00783 // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a 00784 // spurious wakeup), then reacquires the `Mutex` and returns. 00785 // 00786 // Requires and ensures that the current thread holds the `Mutex`. 00787 void Wait(Mutex *mu); 00788 00789 // CondVar::WaitWithTimeout() 00790 // 00791 // Atomically releases a `Mutex` and blocks on this condition variable. 00792 // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a 00793 // spurious wakeup), or until the timeout has expired, then reacquires 00794 // the `Mutex` and returns. 00795 // 00796 // Returns true if the timeout has expired without this `CondVar` 00797 // being signalled in any manner. If both the timeout has expired 00798 // and this `CondVar` has been signalled, the implementation is free 00799 // to return `true` or `false`. 00800 // 00801 // Requires and ensures that the current thread holds the `Mutex`. 00802 bool WaitWithTimeout(Mutex *mu, absl::Duration timeout); 00803 00804 // CondVar::WaitWithDeadline() 00805 // 00806 // Atomically releases a `Mutex` and blocks on this condition variable. 00807 // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a 00808 // spurious wakeup), or until the deadline has passed, then reacquires 00809 // the `Mutex` and returns. 00810 // 00811 // Deadlines in the past are equivalent to an immediate deadline. 00812 // 00813 // Returns true if the deadline has passed without this `CondVar` 00814 // being signalled in any manner. If both the deadline has passed 00815 // and this `CondVar` has been signalled, the implementation is free 00816 // to return `true` or `false`. 00817 // 00818 // Requires and ensures that the current thread holds the `Mutex`. 00819 bool WaitWithDeadline(Mutex *mu, absl::Time deadline); 00820 00821 // CondVar::Signal() 00822 // 00823 // Signal this `CondVar`; wake at least one waiter if one exists. 00824 void Signal(); 00825 00826 // CondVar::SignalAll() 00827 // 00828 // Signal this `CondVar`; wake all waiters. 00829 void SignalAll(); 00830 00831 // CondVar::EnableDebugLog() 00832 // 00833 // Causes all subsequent uses of this `CondVar` to be logged via 00834 // `ABSL_RAW_LOG(INFO)`. Log entries are tagged with `name` if `name != 0`. 00835 // Note: this method substantially reduces `CondVar` performance. 00836 void EnableDebugLog(const char *name); 00837 00838 private: 00839 #ifdef ABSL_INTERNAL_USE_NONPROD_MUTEX 00840 synchronization_internal::CondVarImpl *impl() { return impl_.get(); } 00841 synchronization_internal::SynchronizationStorage< 00842 synchronization_internal::CondVarImpl> 00843 impl_; 00844 #else 00845 bool WaitCommon(Mutex *mutex, synchronization_internal::KernelTimeout t); 00846 void Remove(base_internal::PerThreadSynch *s); 00847 void Wakeup(base_internal::PerThreadSynch *w); 00848 std::atomic<intptr_t> cv_; // Condition variable state. 00849 #endif 00850 CondVar(const CondVar&) = delete; 00851 CondVar& operator=(const CondVar&) = delete; 00852 }; 00853 00854 00855 // Variants of MutexLock. 00856 // 00857 // If you find yourself using one of these, consider instead using 00858 // Mutex::Unlock() and/or if-statements for clarity. 00859 00860 // MutexLockMaybe 00861 // 00862 // MutexLockMaybe is like MutexLock, but is a no-op when mu is null. 00863 class SCOPED_LOCKABLE MutexLockMaybe { 00864 public: 00865 explicit MutexLockMaybe(Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) 00866 : mu_(mu) { if (this->mu_ != nullptr) { this->mu_->Lock(); } } 00867 ~MutexLockMaybe() UNLOCK_FUNCTION() { 00868 if (this->mu_ != nullptr) { this->mu_->Unlock(); } 00869 } 00870 private: 00871 Mutex *const mu_; 00872 MutexLockMaybe(const MutexLockMaybe&) = delete; 00873 MutexLockMaybe(MutexLockMaybe&&) = delete; 00874 MutexLockMaybe& operator=(const MutexLockMaybe&) = delete; 00875 MutexLockMaybe& operator=(MutexLockMaybe&&) = delete; 00876 }; 00877 00878 // ReleasableMutexLock 00879 // 00880 // ReleasableMutexLock is like MutexLock, but permits `Release()` of its 00881 // mutex before destruction. `Release()` may be called at most once. 00882 class SCOPED_LOCKABLE ReleasableMutexLock { 00883 public: 00884 explicit ReleasableMutexLock(Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) 00885 : mu_(mu) { 00886 this->mu_->Lock(); 00887 } 00888 ~ReleasableMutexLock() UNLOCK_FUNCTION() { 00889 if (this->mu_ != nullptr) { this->mu_->Unlock(); } 00890 } 00891 00892 void Release() UNLOCK_FUNCTION(); 00893 00894 private: 00895 Mutex *mu_; 00896 ReleasableMutexLock(const ReleasableMutexLock&) = delete; 00897 ReleasableMutexLock(ReleasableMutexLock&&) = delete; 00898 ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete; 00899 ReleasableMutexLock& operator=(ReleasableMutexLock&&) = delete; 00900 }; 00901 00902 #ifdef ABSL_INTERNAL_USE_NONPROD_MUTEX 00903 inline constexpr Mutex::Mutex(absl::ConstInitType) : impl_(absl::kConstInit) {} 00904 00905 #else 00906 inline Mutex::Mutex() : mu_(0) { 00907 ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static); 00908 } 00909 00910 inline constexpr Mutex::Mutex(absl::ConstInitType) : mu_(0) {} 00911 00912 inline CondVar::CondVar() : cv_(0) {} 00913 #endif 00914 00915 // static 00916 template <typename T> 00917 bool Condition::CastAndCallMethod(const Condition *c) { 00918 typedef bool (T::*MemberType)(); 00919 MemberType rm = reinterpret_cast<MemberType>(c->method_); 00920 T *x = static_cast<T *>(c->arg_); 00921 return (x->*rm)(); 00922 } 00923 00924 // static 00925 template <typename T> 00926 bool Condition::CastAndCallFunction(const Condition *c) { 00927 typedef bool (*FuncType)(T *); 00928 FuncType fn = reinterpret_cast<FuncType>(c->function_); 00929 T *x = static_cast<T *>(c->arg_); 00930 return (*fn)(x); 00931 } 00932 00933 template <typename T> 00934 inline Condition::Condition(bool (*func)(T *), T *arg) 00935 : eval_(&CastAndCallFunction<T>), 00936 function_(reinterpret_cast<InternalFunctionType>(func)), 00937 method_(nullptr), 00938 arg_(const_cast<void *>(static_cast<const void *>(arg))) {} 00939 00940 template <typename T> 00941 inline Condition::Condition(T *object, 00942 bool (absl::internal::identity<T>::type::*method)()) 00943 : eval_(&CastAndCallMethod<T>), 00944 function_(nullptr), 00945 method_(reinterpret_cast<InternalMethodType>(method)), 00946 arg_(object) {} 00947 00948 template <typename T> 00949 inline Condition::Condition(const T *object, 00950 bool (absl::internal::identity<T>::type::*method)() 00951 const) 00952 : eval_(&CastAndCallMethod<T>), 00953 function_(nullptr), 00954 method_(reinterpret_cast<InternalMethodType>(method)), 00955 arg_(reinterpret_cast<void *>(const_cast<T *>(object))) {} 00956 00957 // Register a hook for profiling support. 00958 // 00959 // The function pointer registered here will be called whenever a mutex is 00960 // contended. The callback is given the absl/base/cycleclock.h timestamp when 00961 // waiting began. 00962 // 00963 // Calls to this function do not race or block, but there is no ordering 00964 // guaranteed between calls to this function and call to the provided hook. 00965 // In particular, the previously registered hook may still be called for some 00966 // time after this function returns. 00967 void RegisterMutexProfiler(void (*fn)(int64_t wait_timestamp)); 00968 00969 // Register a hook for Mutex tracing. 00970 // 00971 // The function pointer registered here will be called whenever a mutex is 00972 // contended. The callback is given an opaque handle to the contended mutex, 00973 // an event name, and the number of wait cycles (as measured by 00974 // //absl/base/internal/cycleclock.h, and which may not be real 00975 // "cycle" counts.) 00976 // 00977 // The only event name currently sent is "slow release". 00978 // 00979 // This has the same memory ordering concerns as RegisterMutexProfiler() above. 00980 void RegisterMutexTracer(void (*fn)(const char *msg, const void *obj, 00981 int64_t wait_cycles)); 00982 00983 // TODO(gfalcon): Combine RegisterMutexProfiler() and RegisterMutexTracer() 00984 // into a single interface, since they are only ever called in pairs. 00985 00986 // Register a hook for CondVar tracing. 00987 // 00988 // The function pointer registered here will be called here on various CondVar 00989 // events. The callback is given an opaque handle to the CondVar object and 00990 // a string identifying the event. This is thread-safe, but only a single 00991 // tracer can be registered. 00992 // 00993 // Events that can be sent are "Wait", "Unwait", "Signal wakeup", and 00994 // "SignalAll wakeup". 00995 // 00996 // This has the same memory ordering concerns as RegisterMutexProfiler() above. 00997 void RegisterCondVarTracer(void (*fn)(const char *msg, const void *cv)); 00998 00999 // Register a hook for symbolizing stack traces in deadlock detector reports. 01000 // 01001 // 'pc' is the program counter being symbolized, 'out' is the buffer to write 01002 // into, and 'out_size' is the size of the buffer. This function can return 01003 // false if symbolizing failed, or true if a null-terminated symbol was written 01004 // to 'out.' 01005 // 01006 // This has the same memory ordering concerns as RegisterMutexProfiler() above. 01007 // 01008 // DEPRECATED: The default symbolizer function is absl::Symbolize() and the 01009 // ability to register a different hook for symbolizing stack traces will be 01010 // removed on or after 2023-05-01. 01011 ABSL_DEPRECATED("absl::RegisterSymbolizer() is deprecated and will be removed " 01012 "on or after 2023-05-01") 01013 void RegisterSymbolizer(bool (*fn)(const void *pc, char *out, int out_size)); 01014 01015 // EnableMutexInvariantDebugging() 01016 // 01017 // Enable or disable global support for Mutex invariant debugging. If enabled, 01018 // then invariant predicates can be registered per-Mutex for debug checking. 01019 // See Mutex::EnableInvariantDebugging(). 01020 void EnableMutexInvariantDebugging(bool enabled); 01021 01022 // When in debug mode, and when the feature has been enabled globally, the 01023 // implementation will keep track of lock ordering and complain (or optionally 01024 // crash) if a cycle is detected in the acquired-before graph. 01025 01026 // Possible modes of operation for the deadlock detector in debug mode. 01027 enum class OnDeadlockCycle { 01028 kIgnore, // Neither report on nor attempt to track cycles in lock ordering 01029 kReport, // Report lock cycles to stderr when detected 01030 kAbort, // Report lock cycles to stderr when detected, then abort 01031 }; 01032 01033 // SetMutexDeadlockDetectionMode() 01034 // 01035 // Enable or disable global support for detection of potential deadlocks 01036 // due to Mutex lock ordering inversions. When set to 'kIgnore', tracking of 01037 // lock ordering is disabled. Otherwise, in debug builds, a lock ordering graph 01038 // will be maintained internally, and detected cycles will be reported in 01039 // the manner chosen here. 01040 void SetMutexDeadlockDetectionMode(OnDeadlockCycle mode); 01041 01042 } // namespace absl 01043 01044 // In some build configurations we pass --detect-odr-violations to the 01045 // gold linker. This causes it to flag weak symbol overrides as ODR 01046 // violations. Because ODR only applies to C++ and not C, 01047 // --detect-odr-violations ignores symbols not mangled with C++ names. 01048 // By changing our extension points to be extern "C", we dodge this 01049 // check. 01050 extern "C" { 01051 void AbslInternalMutexYield(); 01052 } // extern "C" 01053 01054 #endif // ABSL_SYNCHRONIZATION_MUTEX_H_