| OLD | NEW |
| (Empty) |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 // A mutex class, with support for thread annotations. | |
| 6 // | |
| 7 // TODO(vtl): Add support for non-exclusive (reader) locks. | |
| 8 | |
| 9 #ifndef MOJO_EDK_SYSTEM_MUTEX_H_ | |
| 10 #define MOJO_EDK_SYSTEM_MUTEX_H_ | |
| 11 | |
| 12 #include <pthread.h> | |
| 13 | |
| 14 #include "mojo/edk/system/thread_annotations.h" | |
| 15 #include "mojo/public/cpp/system/macros.h" | |
| 16 | |
| 17 namespace mojo { | |
| 18 namespace system { | |
| 19 | |
| 20 // So |Mutex| can friend it. | |
| 21 class CondVar; | |
| 22 | |
| 23 // Mutex ----------------------------------------------------------------------- | |
| 24 | |
| 25 class MOJO_LOCKABLE Mutex { | |
| 26 public: | |
| 27 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) | |
| 28 Mutex() { pthread_mutex_init(&impl_, nullptr); } | |
| 29 ~Mutex() { pthread_mutex_destroy(&impl_); } | |
| 30 | |
| 31 // Takes an exclusive lock. | |
| 32 void Lock() MOJO_EXCLUSIVE_LOCK_FUNCTION() { pthread_mutex_lock(&impl_); } | |
| 33 | |
| 34 // Releases a lock. | |
| 35 void Unlock() MOJO_UNLOCK_FUNCTION() { pthread_mutex_unlock(&impl_); } | |
| 36 | |
| 37 // Tries to take an exclusive lock, returning true if successful. | |
| 38 bool TryLock() MOJO_EXCLUSIVE_TRYLOCK_FUNCTION(true) { | |
| 39 return !pthread_mutex_trylock(&impl_); | |
| 40 } | |
| 41 | |
| 42 // Asserts that an exclusive lock is held by the calling thread. (Does nothing | |
| 43 // for non-Debug builds.) | |
| 44 void AssertHeld() MOJO_ASSERT_EXCLUSIVE_LOCK() {} | |
| 45 #else | |
| 46 Mutex(); | |
| 47 ~Mutex(); | |
| 48 | |
| 49 void Lock() MOJO_EXCLUSIVE_LOCK_FUNCTION(); | |
| 50 void Unlock() MOJO_UNLOCK_FUNCTION(); | |
| 51 | |
| 52 bool TryLock() MOJO_EXCLUSIVE_TRYLOCK_FUNCTION(true); | |
| 53 | |
| 54 void AssertHeld() MOJO_ASSERT_EXCLUSIVE_LOCK(); | |
| 55 #endif // defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) | |
| 56 | |
| 57 private: | |
| 58 friend class CondVar; | |
| 59 | |
| 60 pthread_mutex_t impl_; | |
| 61 | |
| 62 MOJO_DISALLOW_COPY_AND_ASSIGN(Mutex); | |
| 63 }; | |
| 64 | |
| 65 // MutexLocker ----------------------------------------------------------------- | |
| 66 | |
| 67 class MOJO_SCOPED_LOCKABLE MutexLocker { | |
| 68 public: | |
| 69 explicit MutexLocker(Mutex* mutex) MOJO_EXCLUSIVE_LOCK_FUNCTION(mutex) | |
| 70 : mutex_(mutex) { | |
| 71 this->mutex_->Lock(); | |
| 72 } | |
| 73 ~MutexLocker() MOJO_UNLOCK_FUNCTION() { this->mutex_->Unlock(); } | |
| 74 | |
| 75 private: | |
| 76 Mutex* const mutex_; | |
| 77 | |
| 78 MOJO_DISALLOW_COPY_AND_ASSIGN(MutexLocker); | |
| 79 }; | |
| 80 | |
| 81 } // namespace system | |
| 82 } // namespace mojo | |
| 83 | |
| 84 #endif // MOJO_EDK_SYSTEM_MUTEX_H_ | |
| OLD | NEW |