| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 |
| 11 | #ifndef RTC_BASE_SYNCHRONIZATION_MUTEX_H_ |
| 12 | #define RTC_BASE_SYNCHRONIZATION_MUTEX_H_ |
| 13 |
| 14 | #include <atomic> |
| 15 |
| 16 | #include "absl/base/attributes.h" |
| 17 | #include "absl/base/const_init.h" |
| 18 | #include "rtc_base/checks.h" |
| 19 | #include "rtc_base/thread_annotations.h" |
| 20 |
| 21 | #if defined(WEBRTC_ABSL_MUTEX) |
| 22 | #include "rtc_base/synchronization/mutex_abseil.h" // nogncheck |
| 23 | #elif defined(WEBRTC_WIN) |
| 24 | #include "rtc_base/synchronization/mutex_critical_section.h" |
| 25 | #elif defined(WEBRTC_POSIX) |
| 26 | #include "rtc_base/synchronization/mutex_pthread.h" |
| 27 | #else |
| 28 | #error Unsupported platform. |
| 29 | #endif |
| 30 |
| 31 | namespace webrtc { |
| 32 |
| 33 | // The Mutex guarantees exclusive access and aims to follow Abseil semantics |
| 34 | // (i.e. non-reentrant etc). |
| 35 | class RTC_LOCKABLE Mutex final { |
| 36 | public: |
| 37 | Mutex() = default; |
| 38 | Mutex(const Mutex&) = delete; |
| 39 | Mutex& operator=(const Mutex&) = delete; |
| 40 |
| 41 | void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { impl_.Lock(); } |
| 42 | ABSL_MUST_USE_RESULT bool TryLock() RTC_EXCLUSIVE_TRYLOCK_FUNCTION(true) { |
| 43 | return impl_.TryLock(); |
| 44 | } |
| 45 | // Return immediately if this thread holds the mutex, or RTC_DCHECK_IS_ON==0. |
| 46 | // Otherwise, may report an error (typically by crashing with a diagnostic), |
| 47 | // or may return immediately. |
| 48 | void AssertHeld() const RTC_ASSERT_EXCLUSIVE_LOCK() { impl_.AssertHeld(); } |
| 49 | void Unlock() RTC_UNLOCK_FUNCTION() { impl_.Unlock(); } |
| 50 |
| 51 | private: |
| 52 | MutexImpl impl_; |
| 53 | }; |
| 54 |
| 55 | // MutexLock, for serializing execution through a scope. |
| 56 | class RTC_SCOPED_LOCKABLE MutexLock final { |
| 57 | public: |
| 58 | MutexLock(const MutexLock&) = delete; |
| 59 | MutexLock& operator=(const MutexLock&) = delete; |
| 60 |
| 61 | explicit MutexLock(Mutex* mutex) RTC_EXCLUSIVE_LOCK_FUNCTION(mutex) |
| 62 | : mutex_(mutex) { |
| 63 | mutex->Lock(); |
| 64 | } |
| 65 | ~MutexLock() RTC_UNLOCK_FUNCTION() { mutex_->Unlock(); } |
| 66 |
| 67 | private: |
| 68 | Mutex* mutex_; |
| 69 | }; |
| 70 |
| 71 | } // namespace webrtc |
| 72 |
| 73 | #endif // RTC_BASE_SYNCHRONIZATION_MUTEX_H_ |
| 74 |