/src/abseil-cpp/absl/synchronization/mutex.h
Line | Count | Source (jump to first uncovered line) |
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. |
279 | 1 | void WriterLock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { this->Lock(); } |
280 | | |
281 | 1 | void WriterUnlock() ABSL_UNLOCK_FUNCTION() { this->Unlock(); } |
282 | | |
283 | 0 | bool WriterTryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) { |
284 | 0 | return this->TryLock(); |
285 | 0 | } |
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 | 0 | void Await(const Condition& cond) { |
328 | 0 | AwaitCommon(cond, synchronization_internal::KernelTimeout::Never()); |
329 | 0 | } |
330 | | |
331 | | // Mutex::LockWhen() |
332 | | // Mutex::ReaderLockWhen() |
333 | | // Mutex::WriterLockWhen() |
334 | | // |
335 | | // Blocks until simultaneously both `cond` is `true` and this `Mutex` can |
336 | | // be acquired, then atomically acquires this `Mutex`. `LockWhen()` is |
337 | | // logically equivalent to `*Lock(); Await();` though they may have different |
338 | | // performance characteristics. |
339 | 0 | void LockWhen(const Condition& cond) ABSL_EXCLUSIVE_LOCK_FUNCTION() { |
340 | 0 | LockWhenCommon(cond, synchronization_internal::KernelTimeout::Never(), |
341 | 0 | true); |
342 | 0 | } |
343 | | |
344 | 0 | void ReaderLockWhen(const Condition& cond) ABSL_SHARED_LOCK_FUNCTION() { |
345 | 0 | LockWhenCommon(cond, synchronization_internal::KernelTimeout::Never(), |
346 | 0 | false); |
347 | 0 | } |
348 | | |
349 | 0 | void WriterLockWhen(const Condition& cond) ABSL_EXCLUSIVE_LOCK_FUNCTION() { |
350 | 0 | this->LockWhen(cond); |
351 | 0 | } |
352 | | |
353 | | // --------------------------------------------------------------------------- |
354 | | // Mutex Variants with Timeouts/Deadlines |
355 | | // --------------------------------------------------------------------------- |
356 | | |
357 | | // Mutex::AwaitWithTimeout() |
358 | | // Mutex::AwaitWithDeadline() |
359 | | // |
360 | | // Unlocks this `Mutex` and blocks until simultaneously: |
361 | | // - either `cond` is true or the {timeout has expired, deadline has passed} |
362 | | // and |
363 | | // - this `Mutex` can be reacquired, |
364 | | // then reacquire this `Mutex` in the same mode in which it was previously |
365 | | // held, returning `true` iff `cond` is `true` on return. |
366 | | // |
367 | | // If the condition is initially `true`, the implementation *may* skip the |
368 | | // release/re-acquire step and return immediately. |
369 | | // |
370 | | // Deadlines in the past are equivalent to an immediate deadline. |
371 | | // Negative timeouts are equivalent to a zero timeout. |
372 | | // |
373 | | // This method requires that this thread holds this `Mutex` in some mode. |
374 | 0 | bool AwaitWithTimeout(const Condition& cond, absl::Duration timeout) { |
375 | 0 | return AwaitCommon(cond, synchronization_internal::KernelTimeout{timeout}); |
376 | 0 | } |
377 | | |
378 | 0 | bool AwaitWithDeadline(const Condition& cond, absl::Time deadline) { |
379 | 0 | return AwaitCommon(cond, synchronization_internal::KernelTimeout{deadline}); |
380 | 0 | } |
381 | | |
382 | | // Mutex::LockWhenWithTimeout() |
383 | | // Mutex::ReaderLockWhenWithTimeout() |
384 | | // Mutex::WriterLockWhenWithTimeout() |
385 | | // |
386 | | // Blocks until simultaneously both: |
387 | | // - either `cond` is `true` or the timeout has expired, and |
388 | | // - this `Mutex` can be acquired, |
389 | | // then atomically acquires this `Mutex`, returning `true` iff `cond` is |
390 | | // `true` on return. |
391 | | // |
392 | | // Negative timeouts are equivalent to a zero timeout. |
393 | | bool LockWhenWithTimeout(const Condition& cond, absl::Duration timeout) |
394 | 0 | ABSL_EXCLUSIVE_LOCK_FUNCTION() { |
395 | 0 | return LockWhenCommon( |
396 | 0 | cond, synchronization_internal::KernelTimeout{timeout}, true); |
397 | 0 | } |
398 | | bool ReaderLockWhenWithTimeout(const Condition& cond, absl::Duration timeout) |
399 | 0 | ABSL_SHARED_LOCK_FUNCTION() { |
400 | 0 | return LockWhenCommon( |
401 | 0 | cond, synchronization_internal::KernelTimeout{timeout}, false); |
402 | 0 | } |
403 | | bool WriterLockWhenWithTimeout(const Condition& cond, absl::Duration timeout) |
404 | 0 | ABSL_EXCLUSIVE_LOCK_FUNCTION() { |
405 | 0 | return this->LockWhenWithTimeout(cond, timeout); |
406 | 0 | } |
407 | | |
408 | | // Mutex::LockWhenWithDeadline() |
409 | | // Mutex::ReaderLockWhenWithDeadline() |
410 | | // Mutex::WriterLockWhenWithDeadline() |
411 | | // |
412 | | // Blocks until simultaneously both: |
413 | | // - either `cond` is `true` or the deadline has been passed, and |
414 | | // - this `Mutex` can be acquired, |
415 | | // then atomically acquires this Mutex, returning `true` iff `cond` is `true` |
416 | | // on return. |
417 | | // |
418 | | // Deadlines in the past are equivalent to an immediate deadline. |
419 | | bool LockWhenWithDeadline(const Condition& cond, absl::Time deadline) |
420 | 0 | ABSL_EXCLUSIVE_LOCK_FUNCTION() { |
421 | 0 | return LockWhenCommon( |
422 | 0 | cond, synchronization_internal::KernelTimeout{deadline}, true); |
423 | 0 | } |
424 | | bool ReaderLockWhenWithDeadline(const Condition& cond, absl::Time deadline) |
425 | 0 | ABSL_SHARED_LOCK_FUNCTION() { |
426 | 0 | return LockWhenCommon( |
427 | 0 | cond, synchronization_internal::KernelTimeout{deadline}, false); |
428 | 0 | } |
429 | | bool WriterLockWhenWithDeadline(const Condition& cond, absl::Time deadline) |
430 | 0 | ABSL_EXCLUSIVE_LOCK_FUNCTION() { |
431 | 0 | return this->LockWhenWithDeadline(cond, deadline); |
432 | 0 | } |
433 | | |
434 | | // --------------------------------------------------------------------------- |
435 | | // Debug Support: Invariant Checking, Deadlock Detection, Logging. |
436 | | // --------------------------------------------------------------------------- |
437 | | |
438 | | // Mutex::EnableInvariantDebugging() |
439 | | // |
440 | | // If `invariant`!=null and if invariant debugging has been enabled globally, |
441 | | // cause `(*invariant)(arg)` to be called at moments when the invariant for |
442 | | // this `Mutex` should hold (for example: just after acquire, just before |
443 | | // release). |
444 | | // |
445 | | // The routine `invariant` should have no side-effects since it is not |
446 | | // guaranteed how many times it will be called; it should check the invariant |
447 | | // and crash if it does not hold. Enabling global invariant debugging may |
448 | | // substantially reduce `Mutex` performance; it should be set only for |
449 | | // non-production runs. Optimization options may also disable invariant |
450 | | // checks. |
451 | | void EnableInvariantDebugging(void (*invariant)(void*), void* arg); |
452 | | |
453 | | // Mutex::EnableDebugLog() |
454 | | // |
455 | | // Cause all subsequent uses of this `Mutex` to be logged via |
456 | | // `ABSL_RAW_LOG(INFO)`. Log entries are tagged with `name` if no previous |
457 | | // call to `EnableInvariantDebugging()` or `EnableDebugLog()` has been made. |
458 | | // |
459 | | // Note: This method substantially reduces `Mutex` performance. |
460 | | void EnableDebugLog(const char* name); |
461 | | |
462 | | // Deadlock detection |
463 | | |
464 | | // Mutex::ForgetDeadlockInfo() |
465 | | // |
466 | | // Forget any deadlock-detection information previously gathered |
467 | | // about this `Mutex`. Call this method in debug mode when the lock ordering |
468 | | // of a `Mutex` changes. |
469 | | void ForgetDeadlockInfo(); |
470 | | |
471 | | // Mutex::AssertNotHeld() |
472 | | // |
473 | | // Return immediately if this thread does not hold this `Mutex` in any |
474 | | // mode; otherwise, may report an error (typically by crashing with a |
475 | | // diagnostic), or may return immediately. |
476 | | // |
477 | | // Currently this check is performed only if all of: |
478 | | // - in debug mode |
479 | | // - SetMutexDeadlockDetectionMode() has been set to kReport or kAbort |
480 | | // - number of locks concurrently held by this thread is not large. |
481 | | // are true. |
482 | | void AssertNotHeld() const; |
483 | | |
484 | | // Special cases. |
485 | | |
486 | | // A `MuHow` is a constant that indicates how a lock should be acquired. |
487 | | // Internal implementation detail. Clients should ignore. |
488 | | typedef const struct MuHowS* MuHow; |
489 | | |
490 | | // Mutex::InternalAttemptToUseMutexInFatalSignalHandler() |
491 | | // |
492 | | // Causes the `Mutex` implementation to prepare itself for re-entry caused by |
493 | | // future use of `Mutex` within a fatal signal handler. This method is |
494 | | // intended for use only for last-ditch attempts to log crash information. |
495 | | // It does not guarantee that attempts to use Mutexes within the handler will |
496 | | // not deadlock; it merely makes other faults less likely. |
497 | | // |
498 | | // WARNING: This routine must be invoked from a signal handler, and the |
499 | | // signal handler must either loop forever or terminate the process. |
500 | | // Attempts to return from (or `longjmp` out of) the signal handler once this |
501 | | // call has been made may cause arbitrary program behaviour including |
502 | | // crashes and deadlocks. |
503 | | static void InternalAttemptToUseMutexInFatalSignalHandler(); |
504 | | |
505 | | private: |
506 | | std::atomic<intptr_t> mu_; // The Mutex state. |
507 | | |
508 | | // Post()/Wait() versus associated PerThreadSem; in class for required |
509 | | // friendship with PerThreadSem. |
510 | | static void IncrementSynchSem(Mutex* mu, base_internal::PerThreadSynch* w); |
511 | | static bool DecrementSynchSem(Mutex* mu, base_internal::PerThreadSynch* w, |
512 | | synchronization_internal::KernelTimeout t); |
513 | | |
514 | | // slow path acquire |
515 | | void LockSlowLoop(SynchWaitParams* waitp, int flags); |
516 | | // wrappers around LockSlowLoop() |
517 | | bool LockSlowWithDeadline(MuHow how, const Condition* cond, |
518 | | synchronization_internal::KernelTimeout t, |
519 | | int flags); |
520 | | void LockSlow(MuHow how, const Condition* cond, |
521 | | int flags) ABSL_ATTRIBUTE_COLD; |
522 | | // slow path release |
523 | | void UnlockSlow(SynchWaitParams* waitp) ABSL_ATTRIBUTE_COLD; |
524 | | // TryLock slow path. |
525 | | bool TryLockSlow(); |
526 | | // ReaderTryLock slow path. |
527 | | bool ReaderTryLockSlow(); |
528 | | // Common code between Await() and AwaitWithTimeout/Deadline() |
529 | | bool AwaitCommon(const Condition& cond, |
530 | | synchronization_internal::KernelTimeout t); |
531 | | bool LockWhenCommon(const Condition& cond, |
532 | | synchronization_internal::KernelTimeout t, bool write); |
533 | | // Attempt to remove thread s from queue. |
534 | | void TryRemove(base_internal::PerThreadSynch* s); |
535 | | // Block a thread on mutex. |
536 | | void Block(base_internal::PerThreadSynch* s); |
537 | | // Wake a thread; return successor. |
538 | | base_internal::PerThreadSynch* Wakeup(base_internal::PerThreadSynch* w); |
539 | | |
540 | | friend class CondVar; // for access to Trans()/Fer(). |
541 | | void Trans(MuHow how); // used for CondVar->Mutex transfer |
542 | | void Fer( |
543 | | base_internal::PerThreadSynch* w); // used for CondVar->Mutex transfer |
544 | | |
545 | | // Catch the error of writing Mutex when intending MutexLock. |
546 | 0 | explicit Mutex(const volatile Mutex* /*ignored*/) {} |
547 | | |
548 | | Mutex(const Mutex&) = delete; |
549 | | Mutex& operator=(const Mutex&) = delete; |
550 | | }; |
551 | | |
552 | | // ----------------------------------------------------------------------------- |
553 | | // Mutex RAII Wrappers |
554 | | // ----------------------------------------------------------------------------- |
555 | | |
556 | | // MutexLock |
557 | | // |
558 | | // `MutexLock` is a helper class, which acquires and releases a `Mutex` via |
559 | | // RAII. |
560 | | // |
561 | | // Example: |
562 | | // |
563 | | // Class Foo { |
564 | | // public: |
565 | | // Foo::Bar* Baz() { |
566 | | // MutexLock lock(&mu_); |
567 | | // ... |
568 | | // return bar; |
569 | | // } |
570 | | // |
571 | | // private: |
572 | | // Mutex mu_; |
573 | | // }; |
574 | | class ABSL_SCOPED_LOCKABLE MutexLock { |
575 | | public: |
576 | | // Constructors |
577 | | |
578 | | // Calls `mu->Lock()` and returns when that call returns. That is, `*mu` is |
579 | | // guaranteed to be locked when this object is constructed. Requires that |
580 | | // `mu` be dereferenceable. |
581 | 40 | explicit MutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) { |
582 | 40 | this->mu_->Lock(); |
583 | 40 | } |
584 | | |
585 | | // Like above, but calls `mu->LockWhen(cond)` instead. That is, in addition to |
586 | | // the above, the condition given by `cond` is also guaranteed to hold when |
587 | | // this object is constructed. |
588 | | explicit MutexLock(Mutex* mu, const Condition& cond) |
589 | | ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) |
590 | 0 | : mu_(mu) { |
591 | 0 | this->mu_->LockWhen(cond); |
592 | 0 | } |
593 | | |
594 | | MutexLock(const MutexLock&) = delete; // NOLINT(runtime/mutex) |
595 | | MutexLock(MutexLock&&) = delete; // NOLINT(runtime/mutex) |
596 | | MutexLock& operator=(const MutexLock&) = delete; |
597 | | MutexLock& operator=(MutexLock&&) = delete; |
598 | | |
599 | 40 | ~MutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_->Unlock(); } |
600 | | |
601 | | private: |
602 | | Mutex* const mu_; |
603 | | }; |
604 | | |
605 | | // ReaderMutexLock |
606 | | // |
607 | | // The `ReaderMutexLock` is a helper class, like `MutexLock`, which acquires and |
608 | | // releases a shared lock on a `Mutex` via RAII. |
609 | | class ABSL_SCOPED_LOCKABLE ReaderMutexLock { |
610 | | public: |
611 | 3.24M | explicit ReaderMutexLock(Mutex* mu) ABSL_SHARED_LOCK_FUNCTION(mu) : mu_(mu) { |
612 | 3.24M | mu->ReaderLock(); |
613 | 3.24M | } |
614 | | |
615 | | explicit ReaderMutexLock(Mutex* mu, const Condition& cond) |
616 | | ABSL_SHARED_LOCK_FUNCTION(mu) |
617 | 0 | : mu_(mu) { |
618 | 0 | mu->ReaderLockWhen(cond); |
619 | 0 | } |
620 | | |
621 | | ReaderMutexLock(const ReaderMutexLock&) = delete; |
622 | | ReaderMutexLock(ReaderMutexLock&&) = delete; |
623 | | ReaderMutexLock& operator=(const ReaderMutexLock&) = delete; |
624 | | ReaderMutexLock& operator=(ReaderMutexLock&&) = delete; |
625 | | |
626 | 3.24M | ~ReaderMutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_->ReaderUnlock(); } |
627 | | |
628 | | private: |
629 | | Mutex* const mu_; |
630 | | }; |
631 | | |
632 | | // WriterMutexLock |
633 | | // |
634 | | // The `WriterMutexLock` is a helper class, like `MutexLock`, which acquires and |
635 | | // releases a write (exclusive) lock on a `Mutex` via RAII. |
636 | | class ABSL_SCOPED_LOCKABLE WriterMutexLock { |
637 | | public: |
638 | | explicit WriterMutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) |
639 | 1 | : mu_(mu) { |
640 | 1 | mu->WriterLock(); |
641 | 1 | } |
642 | | |
643 | | explicit WriterMutexLock(Mutex* mu, const Condition& cond) |
644 | | ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) |
645 | 0 | : mu_(mu) { |
646 | 0 | mu->WriterLockWhen(cond); |
647 | 0 | } |
648 | | |
649 | | WriterMutexLock(const WriterMutexLock&) = delete; |
650 | | WriterMutexLock(WriterMutexLock&&) = delete; |
651 | | WriterMutexLock& operator=(const WriterMutexLock&) = delete; |
652 | | WriterMutexLock& operator=(WriterMutexLock&&) = delete; |
653 | | |
654 | 1 | ~WriterMutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_->WriterUnlock(); } |
655 | | |
656 | | private: |
657 | | Mutex* const mu_; |
658 | | }; |
659 | | |
660 | | // ----------------------------------------------------------------------------- |
661 | | // Condition |
662 | | // ----------------------------------------------------------------------------- |
663 | | // |
664 | | // `Mutex` contains a number of member functions which take a `Condition` as an |
665 | | // argument; clients can wait for conditions to become `true` before attempting |
666 | | // to acquire the mutex. These sections are known as "condition critical" |
667 | | // sections. To use a `Condition`, you simply need to construct it, and use |
668 | | // within an appropriate `Mutex` member function; everything else in the |
669 | | // `Condition` class is an implementation detail. |
670 | | // |
671 | | // A `Condition` is specified as a function pointer which returns a boolean. |
672 | | // `Condition` functions should be pure functions -- their results should depend |
673 | | // only on passed arguments, should not consult any external state (such as |
674 | | // clocks), and should have no side-effects, aside from debug logging. Any |
675 | | // objects that the function may access should be limited to those which are |
676 | | // constant while the mutex is blocked on the condition (e.g. a stack variable), |
677 | | // or objects of state protected explicitly by the mutex. |
678 | | // |
679 | | // No matter which construction is used for `Condition`, the underlying |
680 | | // function pointer / functor / callable must not throw any |
681 | | // exceptions. Correctness of `Mutex` / `Condition` is not guaranteed in |
682 | | // the face of a throwing `Condition`. (When Abseil is allowed to depend |
683 | | // on C++17, these function pointers will be explicitly marked |
684 | | // `noexcept`; until then this requirement cannot be enforced in the |
685 | | // type system.) |
686 | | // |
687 | | // Note: to use a `Condition`, you need only construct it and pass it to a |
688 | | // suitable `Mutex' member function, such as `Mutex::Await()`, or to the |
689 | | // constructor of one of the scope guard classes. |
690 | | // |
691 | | // Example using LockWhen/Unlock: |
692 | | // |
693 | | // // assume count_ is not internal reference count |
694 | | // int count_ ABSL_GUARDED_BY(mu_); |
695 | | // Condition count_is_zero(+[](int *count) { return *count == 0; }, &count_); |
696 | | // |
697 | | // mu_.LockWhen(count_is_zero); |
698 | | // // ... |
699 | | // mu_.Unlock(); |
700 | | // |
701 | | // Example using a scope guard: |
702 | | // |
703 | | // { |
704 | | // MutexLock lock(&mu_, count_is_zero); |
705 | | // // ... |
706 | | // } |
707 | | // |
708 | | // When multiple threads are waiting on exactly the same condition, make sure |
709 | | // that they are constructed with the same parameters (same pointer to function |
710 | | // + arg, or same pointer to object + method), so that the mutex implementation |
711 | | // can avoid redundantly evaluating the same condition for each thread. |
712 | | class Condition { |
713 | | public: |
714 | | // A Condition that returns the result of "(*func)(arg)" |
715 | | Condition(bool (*func)(void*), void* arg); |
716 | | |
717 | | // Templated version for people who are averse to casts. |
718 | | // |
719 | | // To use a lambda, prepend it with unary plus, which converts the lambda |
720 | | // into a function pointer: |
721 | | // Condition(+[](T* t) { return ...; }, arg). |
722 | | // |
723 | | // Note: lambdas in this case must contain no bound variables. |
724 | | // |
725 | | // See class comment for performance advice. |
726 | | template <typename T> |
727 | | Condition(bool (*func)(T*), T* arg); |
728 | | |
729 | | // Same as above, but allows for cases where `arg` comes from a pointer that |
730 | | // is convertible to the function parameter type `T*` but not an exact match. |
731 | | // |
732 | | // For example, the argument might be `X*` but the function takes `const X*`, |
733 | | // or the argument might be `Derived*` while the function takes `Base*`, and |
734 | | // so on for cases where the argument pointer can be implicitly converted. |
735 | | // |
736 | | // Implementation notes: This constructor overload is required in addition to |
737 | | // the one above to allow deduction of `T` from `arg` for cases such as where |
738 | | // a function template is passed as `func`. Also, the dummy `typename = void` |
739 | | // template parameter exists just to work around a MSVC mangling bug. |
740 | | template <typename T, typename = void> |
741 | | Condition(bool (*func)(T*), typename absl::internal::identity<T>::type* arg); |
742 | | |
743 | | // Templated version for invoking a method that returns a `bool`. |
744 | | // |
745 | | // `Condition(object, &Class::Method)` constructs a `Condition` that evaluates |
746 | | // `object->Method()`. |
747 | | // |
748 | | // Implementation Note: `absl::internal::identity` is used to allow methods to |
749 | | // come from base classes. A simpler signature like |
750 | | // `Condition(T*, bool (T::*)())` does not suffice. |
751 | | template <typename T> |
752 | | Condition(T* object, bool (absl::internal::identity<T>::type::*method)()); |
753 | | |
754 | | // Same as above, for const members |
755 | | template <typename T> |
756 | | Condition(const T* object, |
757 | | bool (absl::internal::identity<T>::type::*method)() const); |
758 | | |
759 | | // A Condition that returns the value of `*cond` |
760 | | explicit Condition(const bool* cond); |
761 | | |
762 | | // Templated version for invoking a functor that returns a `bool`. |
763 | | // This approach accepts pointers to non-mutable lambdas, `std::function`, |
764 | | // the result of` std::bind` and user-defined functors that define |
765 | | // `bool F::operator()() const`. |
766 | | // |
767 | | // Example: |
768 | | // |
769 | | // auto reached = [this, current]() { |
770 | | // mu_.AssertReaderHeld(); // For annotalysis. |
771 | | // return processed_ >= current; |
772 | | // }; |
773 | | // mu_.Await(Condition(&reached)); |
774 | | // |
775 | | // NOTE: never use "mu_.AssertHeld()" instead of "mu_.AssertReaderHeld()" in |
776 | | // the lambda as it may be called when the mutex is being unlocked from a |
777 | | // scope holding only a reader lock, which will make the assertion not |
778 | | // fulfilled and crash the binary. |
779 | | |
780 | | // See class comment for performance advice. In particular, if there |
781 | | // might be more than one waiter for the same condition, make sure |
782 | | // that all waiters construct the condition with the same pointers. |
783 | | |
784 | | // Implementation note: The second template parameter ensures that this |
785 | | // constructor doesn't participate in overload resolution if T doesn't have |
786 | | // `bool operator() const`. |
787 | | template <typename T, typename E = decltype(static_cast<bool (T::*)() const>( |
788 | | &T::operator()))> |
789 | | explicit Condition(const T* obj) |
790 | | : Condition(obj, static_cast<bool (T::*)() const>(&T::operator())) {} |
791 | | |
792 | | // A Condition that always returns `true`. |
793 | | // kTrue is only useful in a narrow set of circumstances, mostly when |
794 | | // it's passed conditionally. For example: |
795 | | // |
796 | | // mu.LockWhen(some_flag ? kTrue : SomeOtherCondition); |
797 | | // |
798 | | // Note: {LockWhen,Await}With{Deadline,Timeout} methods with kTrue condition |
799 | | // don't return immediately when the timeout happens, they still block until |
800 | | // the Mutex becomes available. The return value of these methods does |
801 | | // not indicate if the timeout was reached; rather it indicates whether or |
802 | | // not the condition is true. |
803 | | ABSL_CONST_INIT static const Condition kTrue; |
804 | | |
805 | | // Evaluates the condition. |
806 | | bool Eval() const; |
807 | | |
808 | | // Returns `true` if the two conditions are guaranteed to return the same |
809 | | // value if evaluated at the same time, `false` if the evaluation *may* return |
810 | | // different results. |
811 | | // |
812 | | // Two `Condition` values are guaranteed equal if both their `func` and `arg` |
813 | | // components are the same. A null pointer is equivalent to a `true` |
814 | | // condition. |
815 | | static bool GuaranteedEqual(const Condition* a, const Condition* b); |
816 | | |
817 | | private: |
818 | | // Sizing an allocation for a method pointer can be subtle. In the Itanium |
819 | | // specifications, a method pointer has a predictable, uniform size. On the |
820 | | // other hand, MSVC ABI, method pointer sizes vary based on the |
821 | | // inheritance of the class. Specifically, method pointers from classes with |
822 | | // multiple inheritance are bigger than those of classes with single |
823 | | // inheritance. Other variations also exist. |
824 | | |
825 | | #ifndef _MSC_VER |
826 | | // Allocation for a function pointer or method pointer. |
827 | | // The {0} initializer ensures that all unused bytes of this buffer are |
828 | | // always zeroed out. This is necessary, because GuaranteedEqual() compares |
829 | | // all of the bytes, unaware of which bytes are relevant to a given `eval_`. |
830 | | using MethodPtr = bool (Condition::*)(); |
831 | | char callback_[sizeof(MethodPtr)] = {0}; |
832 | | #else |
833 | | // It is well known that the larget MSVC pointer-to-member is 24 bytes. This |
834 | | // may be the largest known pointer-to-member of any platform. For this |
835 | | // reason we will allocate 24 bytes for MSVC platform toolchains. |
836 | | char callback_[24] = {0}; |
837 | | #endif |
838 | | |
839 | | // Function with which to evaluate callbacks and/or arguments. |
840 | | bool (*eval_)(const Condition*) = nullptr; |
841 | | |
842 | | // Either an argument for a function call or an object for a method call. |
843 | | void* arg_ = nullptr; |
844 | | |
845 | | // Various functions eval_ can point to: |
846 | | static bool CallVoidPtrFunction(const Condition*); |
847 | | template <typename T> |
848 | | static bool CastAndCallFunction(const Condition* c); |
849 | | template <typename T> |
850 | | static bool CastAndCallMethod(const Condition* c); |
851 | | |
852 | | // Helper methods for storing, validating, and reading callback arguments. |
853 | | template <typename T> |
854 | 0 | inline void StoreCallback(T callback) { |
855 | 0 | static_assert( |
856 | 0 | sizeof(callback) <= sizeof(callback_), |
857 | 0 | "An overlarge pointer was passed as a callback to Condition."); |
858 | 0 | std::memcpy(callback_, &callback, sizeof(callback)); |
859 | 0 | } Unexecuted instantiation: void absl::Condition::StoreCallback<bool (*)(absl::SynchEvent*)>(bool (*)(absl::SynchEvent*)) Unexecuted instantiation: void absl::Condition::StoreCallback<bool (*)(void*)>(bool (*)(void*)) |
860 | | |
861 | | template <typename T> |
862 | 0 | inline void ReadCallback(T* callback) const { |
863 | 0 | std::memcpy(callback, callback_, sizeof(*callback)); |
864 | 0 | } |
865 | | |
866 | 0 | static bool AlwaysTrue(const Condition*) { return true; } |
867 | | |
868 | | // Used only to create kTrue. |
869 | 0 | constexpr Condition() : eval_(AlwaysTrue), arg_(nullptr) {} |
870 | | }; |
871 | | |
872 | | // ----------------------------------------------------------------------------- |
873 | | // CondVar |
874 | | // ----------------------------------------------------------------------------- |
875 | | // |
876 | | // A condition variable, reflecting state evaluated separately outside of the |
877 | | // `Mutex` object, which can be signaled to wake callers. |
878 | | // This class is not normally needed; use `Mutex` member functions such as |
879 | | // `Mutex::Await()` and intrinsic `Condition` abstractions. In rare cases |
880 | | // with many threads and many conditions, `CondVar` may be faster. |
881 | | // |
882 | | // The implementation may deliver signals to any condition variable at |
883 | | // any time, even when no call to `Signal()` or `SignalAll()` is made; as a |
884 | | // result, upon being awoken, you must check the logical condition you have |
885 | | // been waiting upon. |
886 | | // |
887 | | // Examples: |
888 | | // |
889 | | // Usage for a thread waiting for some condition C protected by mutex mu: |
890 | | // mu.Lock(); |
891 | | // while (!C) { cv->Wait(&mu); } // releases and reacquires mu |
892 | | // // C holds; process data |
893 | | // mu.Unlock(); |
894 | | // |
895 | | // Usage to wake T is: |
896 | | // mu.Lock(); |
897 | | // // process data, possibly establishing C |
898 | | // if (C) { cv->Signal(); } |
899 | | // mu.Unlock(); |
900 | | // |
901 | | // If C may be useful to more than one waiter, use `SignalAll()` instead of |
902 | | // `Signal()`. |
903 | | // |
904 | | // With this implementation it is efficient to use `Signal()/SignalAll()` inside |
905 | | // the locked region; this usage can make reasoning about your program easier. |
906 | | // |
907 | | class CondVar { |
908 | | public: |
909 | | // A `CondVar` allocated on the heap or on the stack can use the this |
910 | | // constructor. |
911 | | CondVar(); |
912 | | ~CondVar(); |
913 | | |
914 | | // CondVar::Wait() |
915 | | // |
916 | | // Atomically releases a `Mutex` and blocks on this condition variable. |
917 | | // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a |
918 | | // spurious wakeup), then reacquires the `Mutex` and returns. |
919 | | // |
920 | | // Requires and ensures that the current thread holds the `Mutex`. |
921 | 0 | void Wait(Mutex* mu) { |
922 | 0 | WaitCommon(mu, synchronization_internal::KernelTimeout::Never()); |
923 | 0 | } |
924 | | |
925 | | // CondVar::WaitWithTimeout() |
926 | | // |
927 | | // Atomically releases a `Mutex` and blocks on this condition variable. |
928 | | // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a |
929 | | // spurious wakeup), or until the timeout has expired, then reacquires |
930 | | // the `Mutex` and returns. |
931 | | // |
932 | | // Returns true if the timeout has expired without this `CondVar` |
933 | | // being signalled in any manner. If both the timeout has expired |
934 | | // and this `CondVar` has been signalled, the implementation is free |
935 | | // to return `true` or `false`. |
936 | | // |
937 | | // Requires and ensures that the current thread holds the `Mutex`. |
938 | 0 | bool WaitWithTimeout(Mutex* mu, absl::Duration timeout) { |
939 | 0 | return WaitCommon(mu, synchronization_internal::KernelTimeout(timeout)); |
940 | 0 | } |
941 | | |
942 | | // CondVar::WaitWithDeadline() |
943 | | // |
944 | | // Atomically releases a `Mutex` and blocks on this condition variable. |
945 | | // Waits until awakened by a call to `Signal()` or `SignalAll()` (or a |
946 | | // spurious wakeup), or until the deadline has passed, then reacquires |
947 | | // the `Mutex` and returns. |
948 | | // |
949 | | // Deadlines in the past are equivalent to an immediate deadline. |
950 | | // |
951 | | // Returns true if the deadline has passed without this `CondVar` |
952 | | // being signalled in any manner. If both the deadline has passed |
953 | | // and this `CondVar` has been signalled, the implementation is free |
954 | | // to return `true` or `false`. |
955 | | // |
956 | | // Requires and ensures that the current thread holds the `Mutex`. |
957 | 0 | bool WaitWithDeadline(Mutex* mu, absl::Time deadline) { |
958 | 0 | return WaitCommon(mu, synchronization_internal::KernelTimeout(deadline)); |
959 | 0 | } |
960 | | |
961 | | // CondVar::Signal() |
962 | | // |
963 | | // Signal this `CondVar`; wake at least one waiter if one exists. |
964 | | void Signal(); |
965 | | |
966 | | // CondVar::SignalAll() |
967 | | // |
968 | | // Signal this `CondVar`; wake all waiters. |
969 | | void SignalAll(); |
970 | | |
971 | | // CondVar::EnableDebugLog() |
972 | | // |
973 | | // Causes all subsequent uses of this `CondVar` to be logged via |
974 | | // `ABSL_RAW_LOG(INFO)`. Log entries are tagged with `name` if `name != 0`. |
975 | | // Note: this method substantially reduces `CondVar` performance. |
976 | | void EnableDebugLog(const char* name); |
977 | | |
978 | | private: |
979 | | bool WaitCommon(Mutex* mutex, synchronization_internal::KernelTimeout t); |
980 | | void Remove(base_internal::PerThreadSynch* s); |
981 | | std::atomic<intptr_t> cv_; // Condition variable state. |
982 | | CondVar(const CondVar&) = delete; |
983 | | CondVar& operator=(const CondVar&) = delete; |
984 | | }; |
985 | | |
986 | | // Variants of MutexLock. |
987 | | // |
988 | | // If you find yourself using one of these, consider instead using |
989 | | // Mutex::Unlock() and/or if-statements for clarity. |
990 | | |
991 | | // MutexLockMaybe |
992 | | // |
993 | | // MutexLockMaybe is like MutexLock, but is a no-op when mu is null. |
994 | | class ABSL_SCOPED_LOCKABLE MutexLockMaybe { |
995 | | public: |
996 | | explicit MutexLockMaybe(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) |
997 | 0 | : mu_(mu) { |
998 | 0 | if (this->mu_ != nullptr) { |
999 | 0 | this->mu_->Lock(); |
1000 | 0 | } |
1001 | 0 | } |
1002 | | |
1003 | | explicit MutexLockMaybe(Mutex* mu, const Condition& cond) |
1004 | | ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) |
1005 | 0 | : mu_(mu) { |
1006 | 0 | if (this->mu_ != nullptr) { |
1007 | 0 | this->mu_->LockWhen(cond); |
1008 | 0 | } |
1009 | 0 | } |
1010 | | |
1011 | 0 | ~MutexLockMaybe() ABSL_UNLOCK_FUNCTION() { |
1012 | 0 | if (this->mu_ != nullptr) { |
1013 | 0 | this->mu_->Unlock(); |
1014 | 0 | } |
1015 | 0 | } |
1016 | | |
1017 | | private: |
1018 | | Mutex* const mu_; |
1019 | | MutexLockMaybe(const MutexLockMaybe&) = delete; |
1020 | | MutexLockMaybe(MutexLockMaybe&&) = delete; |
1021 | | MutexLockMaybe& operator=(const MutexLockMaybe&) = delete; |
1022 | | MutexLockMaybe& operator=(MutexLockMaybe&&) = delete; |
1023 | | }; |
1024 | | |
1025 | | // ReleasableMutexLock |
1026 | | // |
1027 | | // ReleasableMutexLock is like MutexLock, but permits `Release()` of its |
1028 | | // mutex before destruction. `Release()` may be called at most once. |
1029 | | class ABSL_SCOPED_LOCKABLE ReleasableMutexLock { |
1030 | | public: |
1031 | | explicit ReleasableMutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) |
1032 | 0 | : mu_(mu) { |
1033 | 0 | this->mu_->Lock(); |
1034 | 0 | } |
1035 | | |
1036 | | explicit ReleasableMutexLock(Mutex* mu, const Condition& cond) |
1037 | | ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) |
1038 | 0 | : mu_(mu) { |
1039 | 0 | this->mu_->LockWhen(cond); |
1040 | 0 | } |
1041 | | |
1042 | 0 | ~ReleasableMutexLock() ABSL_UNLOCK_FUNCTION() { |
1043 | 0 | if (this->mu_ != nullptr) { |
1044 | 0 | this->mu_->Unlock(); |
1045 | 0 | } |
1046 | 0 | } |
1047 | | |
1048 | | void Release() ABSL_UNLOCK_FUNCTION(); |
1049 | | |
1050 | | private: |
1051 | | Mutex* mu_; |
1052 | | ReleasableMutexLock(const ReleasableMutexLock&) = delete; |
1053 | | ReleasableMutexLock(ReleasableMutexLock&&) = delete; |
1054 | | ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete; |
1055 | | ReleasableMutexLock& operator=(ReleasableMutexLock&&) = delete; |
1056 | | }; |
1057 | | |
1058 | 4 | inline Mutex::Mutex() : mu_(0) { |
1059 | 4 | ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static); |
1060 | 4 | } |
1061 | | |
1062 | | inline constexpr Mutex::Mutex(absl::ConstInitType) : mu_(0) {} |
1063 | | |
1064 | | inline CondVar::CondVar() : cv_(0) {} |
1065 | | |
1066 | | // static |
1067 | | template <typename T> |
1068 | | bool Condition::CastAndCallMethod(const Condition* c) { |
1069 | | T* object = static_cast<T*>(c->arg_); |
1070 | | bool (T::*method_pointer)(); |
1071 | | c->ReadCallback(&method_pointer); |
1072 | | return (object->*method_pointer)(); |
1073 | | } |
1074 | | |
1075 | | // static |
1076 | | template <typename T> |
1077 | 0 | bool Condition::CastAndCallFunction(const Condition* c) { |
1078 | 0 | bool (*function)(T*); |
1079 | 0 | c->ReadCallback(&function); |
1080 | 0 | T* argument = static_cast<T*>(c->arg_); |
1081 | 0 | return (*function)(argument); |
1082 | 0 | } |
1083 | | |
1084 | | template <typename T> |
1085 | | inline Condition::Condition(bool (*func)(T*), T* arg) |
1086 | | : eval_(&CastAndCallFunction<T>), |
1087 | 0 | arg_(const_cast<void*>(static_cast<const void*>(arg))) { |
1088 | 0 | static_assert(sizeof(&func) <= sizeof(callback_), |
1089 | 0 | "An overlarge function pointer was passed to Condition."); |
1090 | 0 | StoreCallback(func); |
1091 | 0 | } |
1092 | | |
1093 | | template <typename T, typename> |
1094 | | inline Condition::Condition(bool (*func)(T*), |
1095 | | typename absl::internal::identity<T>::type* arg) |
1096 | | // Just delegate to the overload above. |
1097 | | : Condition(func, arg) {} |
1098 | | |
1099 | | template <typename T> |
1100 | | inline Condition::Condition(T* object, |
1101 | | bool (absl::internal::identity<T>::type::*method)()) |
1102 | | : eval_(&CastAndCallMethod<T>), arg_(object) { |
1103 | | static_assert(sizeof(&method) <= sizeof(callback_), |
1104 | | "An overlarge method pointer was passed to Condition."); |
1105 | | StoreCallback(method); |
1106 | | } |
1107 | | |
1108 | | template <typename T> |
1109 | | inline Condition::Condition(const T* object, |
1110 | | bool (absl::internal::identity<T>::type::*method)() |
1111 | | const) |
1112 | | : eval_(&CastAndCallMethod<T>), |
1113 | | arg_(reinterpret_cast<void*>(const_cast<T*>(object))) { |
1114 | | StoreCallback(method); |
1115 | | } |
1116 | | |
1117 | | // Register hooks for profiling support. |
1118 | | // |
1119 | | // The function pointer registered here will be called whenever a mutex is |
1120 | | // contended. The callback is given the cycles for which waiting happened (as |
1121 | | // measured by //absl/base/internal/cycleclock.h, and which may not |
1122 | | // be real "cycle" counts.) |
1123 | | // |
1124 | | // There is no ordering guarantee between when the hook is registered and when |
1125 | | // callbacks will begin. Only a single profiler can be installed in a running |
1126 | | // binary; if this function is called a second time with a different function |
1127 | | // pointer, the value is ignored (and will cause an assertion failure in debug |
1128 | | // mode.) |
1129 | | void RegisterMutexProfiler(void (*fn)(int64_t wait_cycles)); |
1130 | | |
1131 | | // Register a hook for Mutex tracing. |
1132 | | // |
1133 | | // The function pointer registered here will be called whenever a mutex is |
1134 | | // contended. The callback is given an opaque handle to the contended mutex, |
1135 | | // an event name, and the number of wait cycles (as measured by |
1136 | | // //absl/base/internal/cycleclock.h, and which may not be real |
1137 | | // "cycle" counts.) |
1138 | | // |
1139 | | // The only event name currently sent is "slow release". |
1140 | | // |
1141 | | // This has the same ordering and single-use limitations as |
1142 | | // RegisterMutexProfiler() above. |
1143 | | void RegisterMutexTracer(void (*fn)(const char* msg, const void* obj, |
1144 | | int64_t wait_cycles)); |
1145 | | |
1146 | | // Register a hook for CondVar tracing. |
1147 | | // |
1148 | | // The function pointer registered here will be called here on various CondVar |
1149 | | // events. The callback is given an opaque handle to the CondVar object and |
1150 | | // a string identifying the event. This is thread-safe, but only a single |
1151 | | // tracer can be registered. |
1152 | | // |
1153 | | // Events that can be sent are "Wait", "Unwait", "Signal wakeup", and |
1154 | | // "SignalAll wakeup". |
1155 | | // |
1156 | | // This has the same ordering and single-use limitations as |
1157 | | // RegisterMutexProfiler() above. |
1158 | | void RegisterCondVarTracer(void (*fn)(const char* msg, const void* cv)); |
1159 | | |
1160 | | // EnableMutexInvariantDebugging() |
1161 | | // |
1162 | | // Enable or disable global support for Mutex invariant debugging. If enabled, |
1163 | | // then invariant predicates can be registered per-Mutex for debug checking. |
1164 | | // See Mutex::EnableInvariantDebugging(). |
1165 | | void EnableMutexInvariantDebugging(bool enabled); |
1166 | | |
1167 | | // When in debug mode, and when the feature has been enabled globally, the |
1168 | | // implementation will keep track of lock ordering and complain (or optionally |
1169 | | // crash) if a cycle is detected in the acquired-before graph. |
1170 | | |
1171 | | // Possible modes of operation for the deadlock detector in debug mode. |
1172 | | enum class OnDeadlockCycle { |
1173 | | kIgnore, // Neither report on nor attempt to track cycles in lock ordering |
1174 | | kReport, // Report lock cycles to stderr when detected |
1175 | | kAbort, // Report lock cycles to stderr when detected, then abort |
1176 | | }; |
1177 | | |
1178 | | // SetMutexDeadlockDetectionMode() |
1179 | | // |
1180 | | // Enable or disable global support for detection of potential deadlocks |
1181 | | // due to Mutex lock ordering inversions. When set to 'kIgnore', tracking of |
1182 | | // lock ordering is disabled. Otherwise, in debug builds, a lock ordering graph |
1183 | | // will be maintained internally, and detected cycles will be reported in |
1184 | | // the manner chosen here. |
1185 | | void SetMutexDeadlockDetectionMode(OnDeadlockCycle mode); |
1186 | | |
1187 | | ABSL_NAMESPACE_END |
1188 | | } // namespace absl |
1189 | | |
1190 | | // In some build configurations we pass --detect-odr-violations to the |
1191 | | // gold linker. This causes it to flag weak symbol overrides as ODR |
1192 | | // violations. Because ODR only applies to C++ and not C, |
1193 | | // --detect-odr-violations ignores symbols not mangled with C++ names. |
1194 | | // By changing our extension points to be extern "C", we dodge this |
1195 | | // check. |
1196 | | extern "C" { |
1197 | | void ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)(); |
1198 | | } // extern "C" |
1199 | | |
1200 | | #endif // ABSL_SYNCHRONIZATION_MUTEX_H_ |