Markus Handell | f70fbc8 | 2020-06-04 00:41:20 +0200 | [diff] [blame] | 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_PTHREAD_H_ |
| 12 | #define RTC_BASE_SYNCHRONIZATION_MUTEX_PTHREAD_H_ |
| 13 | |
| 14 | #if defined(WEBRTC_POSIX) |
| 15 | |
| 16 | #include <pthread.h> |
| 17 | #if defined(WEBRTC_MAC) |
| 18 | #include <pthread_spis.h> |
| 19 | #endif |
| 20 | |
Danil Chapovalov | 8c2250e | 2021-01-14 13:31:46 +0100 | [diff] [blame^] | 21 | #include "absl/base/attributes.h" |
Markus Handell | f70fbc8 | 2020-06-04 00:41:20 +0200 | [diff] [blame] | 22 | #include "rtc_base/thread_annotations.h" |
| 23 | |
| 24 | namespace webrtc { |
| 25 | |
| 26 | class RTC_LOCKABLE MutexImpl final { |
| 27 | public: |
| 28 | MutexImpl() { |
| 29 | pthread_mutexattr_t mutex_attribute; |
| 30 | pthread_mutexattr_init(&mutex_attribute); |
| 31 | #if defined(WEBRTC_MAC) |
| 32 | pthread_mutexattr_setpolicy_np(&mutex_attribute, |
Markus Handell | 4a4f162 | 2020-06-05 11:21:10 +0200 | [diff] [blame] | 33 | _PTHREAD_MUTEX_POLICY_FIRSTFIT); |
Markus Handell | f70fbc8 | 2020-06-04 00:41:20 +0200 | [diff] [blame] | 34 | #endif |
| 35 | pthread_mutex_init(&mutex_, &mutex_attribute); |
| 36 | pthread_mutexattr_destroy(&mutex_attribute); |
| 37 | } |
| 38 | MutexImpl(const MutexImpl&) = delete; |
| 39 | MutexImpl& operator=(const MutexImpl&) = delete; |
| 40 | ~MutexImpl() { pthread_mutex_destroy(&mutex_); } |
| 41 | |
| 42 | void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { pthread_mutex_lock(&mutex_); } |
Danil Chapovalov | 8c2250e | 2021-01-14 13:31:46 +0100 | [diff] [blame^] | 43 | ABSL_MUST_USE_RESULT bool TryLock() RTC_EXCLUSIVE_TRYLOCK_FUNCTION(true) { |
Markus Handell | f70fbc8 | 2020-06-04 00:41:20 +0200 | [diff] [blame] | 44 | return pthread_mutex_trylock(&mutex_) == 0; |
| 45 | } |
| 46 | void Unlock() RTC_UNLOCK_FUNCTION() { pthread_mutex_unlock(&mutex_); } |
| 47 | |
| 48 | private: |
| 49 | pthread_mutex_t mutex_; |
| 50 | }; |
| 51 | |
| 52 | } // namespace webrtc |
| 53 | #endif // #if defined(WEBRTC_POSIX) |
| 54 | #endif // RTC_BASE_SYNCHRONIZATION_MUTEX_PTHREAD_H_ |