mutex_pthread.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. #ifndef RTC_BASE_SYNCHRONIZATION_MUTEX_PTHREAD_H_
  11. #define RTC_BASE_SYNCHRONIZATION_MUTEX_PTHREAD_H_
  12. #if defined(WEBRTC_POSIX)
  13. #include <pthread.h>
  14. #if defined(WEBRTC_MAC)
  15. #include <pthread_spis.h>
  16. #endif
  17. #include "rtc_base/thread_annotations.h"
  18. namespace webrtc {
  19. class RTC_LOCKABLE MutexImpl final {
  20. public:
  21. MutexImpl() {
  22. pthread_mutexattr_t mutex_attribute;
  23. pthread_mutexattr_init(&mutex_attribute);
  24. #if defined(WEBRTC_MAC)
  25. pthread_mutexattr_setpolicy_np(&mutex_attribute,
  26. _PTHREAD_MUTEX_POLICY_FIRSTFIT);
  27. #endif
  28. pthread_mutex_init(&mutex_, &mutex_attribute);
  29. pthread_mutexattr_destroy(&mutex_attribute);
  30. }
  31. MutexImpl(const MutexImpl&) = delete;
  32. MutexImpl& operator=(const MutexImpl&) = delete;
  33. ~MutexImpl() { pthread_mutex_destroy(&mutex_); }
  34. void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { pthread_mutex_lock(&mutex_); }
  35. RTC_WARN_UNUSED_RESULT bool TryLock() RTC_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
  36. return pthread_mutex_trylock(&mutex_) == 0;
  37. }
  38. void Unlock() RTC_UNLOCK_FUNCTION() { pthread_mutex_unlock(&mutex_); }
  39. private:
  40. pthread_mutex_t mutex_;
  41. };
  42. } // namespace webrtc
  43. #endif // #if defined(WEBRTC_POSIX)
  44. #endif // RTC_BASE_SYNCHRONIZATION_MUTEX_PTHREAD_H_