| OLD | NEW |
| (Empty) |
| 1 // Copyright 2014 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 #ifndef MOJO_PUBLIC_CPP_UTILITY_MUTEX_H_ | |
| 6 #define MOJO_PUBLIC_CPP_UTILITY_MUTEX_H_ | |
| 7 | |
| 8 #ifdef _WIN32 | |
| 9 #error "Not implemented: See crbug.com/342893." | |
| 10 #endif | |
| 11 | |
| 12 #include <pthread.h> | |
| 13 | |
| 14 #include "base/macros.h" | |
| 15 #include "mojo/public/cpp/system/macros.h" | |
| 16 | |
| 17 namespace mojo { | |
| 18 | |
| 19 #ifdef NDEBUG | |
| 20 // Note: Make a C++ constant for |PTHREAD_MUTEX_INITIALIZER|. (We can't directly | |
| 21 // use the C macro in an initializer list, since it might expand to |{ ... }|.) | |
| 22 namespace internal { | |
| 23 const pthread_mutex_t kPthreadMutexInitializer = PTHREAD_MUTEX_INITIALIZER; | |
| 24 } | |
| 25 #endif | |
| 26 | |
| 27 class Mutex { | |
| 28 public: | |
| 29 #ifdef NDEBUG | |
| 30 Mutex() : mutex_(internal::kPthreadMutexInitializer) {} | |
| 31 ~Mutex() { pthread_mutex_destroy(&mutex_); } | |
| 32 | |
| 33 void Lock() { pthread_mutex_lock(&mutex_); } | |
| 34 void Unlock() { pthread_mutex_unlock(&mutex_); } | |
| 35 bool TryLock() { return pthread_mutex_trylock(&mutex_) == 0; } | |
| 36 | |
| 37 void AssertHeld() {} | |
| 38 #else | |
| 39 Mutex(); | |
| 40 ~Mutex(); | |
| 41 | |
| 42 void Lock(); | |
| 43 void Unlock(); | |
| 44 bool TryLock(); | |
| 45 | |
| 46 void AssertHeld(); | |
| 47 #endif | |
| 48 | |
| 49 private: | |
| 50 pthread_mutex_t mutex_; | |
| 51 | |
| 52 DISALLOW_COPY_AND_ASSIGN(Mutex); | |
| 53 }; | |
| 54 | |
| 55 class MutexLock { | |
| 56 public: | |
| 57 explicit MutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } | |
| 58 ~MutexLock() { mutex_->Unlock(); } | |
| 59 | |
| 60 private: | |
| 61 Mutex* const mutex_; | |
| 62 | |
| 63 DISALLOW_COPY_AND_ASSIGN(MutexLock); | |
| 64 }; | |
| 65 | |
| 66 // Catch bug where variable name is omitted (e.g., |MutexLock (&mu)|). | |
| 67 #define MutexLock(x) static_assert(0, "MutexLock() missing variable name"); | |
| 68 | |
| 69 } // namespace mojo | |
| 70 | |
| 71 #endif // MOJO_PUBLIC_CPP_UTILITY_MUTEX_H_ | |
| OLD | NEW |