1 /* 2 * Copyright 2020 The WebRTC Project Authors. All rights reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 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 Lock()41 void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { 42 impl_.Lock(); 43 } TryLock()44 ABSL_MUST_USE_RESULT bool TryLock() RTC_EXCLUSIVE_TRYLOCK_FUNCTION(true) { 45 return impl_.TryLock(); 46 } 47 // Return immediately if this thread holds the mutex, or RTC_DCHECK_IS_ON==0. 48 // Otherwise, may report an error (typically by crashing with a diagnostic), 49 // or may return immediately. AssertHeld()50 void AssertHeld() const RTC_ASSERT_EXCLUSIVE_LOCK() { impl_.AssertHeld(); } Unlock()51 void Unlock() RTC_UNLOCK_FUNCTION() { 52 impl_.Unlock(); 53 } 54 55 private: 56 MutexImpl impl_; 57 }; 58 59 // MutexLock, for serializing execution through a scope. 60 class RTC_SCOPED_LOCKABLE MutexLock final { 61 public: 62 MutexLock(const MutexLock&) = delete; 63 MutexLock& operator=(const MutexLock&) = delete; 64 MutexLock(Mutex * mutex)65 explicit MutexLock(Mutex* mutex) RTC_EXCLUSIVE_LOCK_FUNCTION(mutex) 66 : mutex_(mutex) { 67 mutex->Lock(); 68 } RTC_UNLOCK_FUNCTION()69 ~MutexLock() RTC_UNLOCK_FUNCTION() { mutex_->Unlock(); } 70 71 private: 72 Mutex* mutex_; 73 }; 74 75 } // namespace webrtc 76 77 #endif // RTC_BASE_SYNCHRONIZATION_MUTEX_H_ 78