Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 1 | #include "aos/common/mutex.h" |
| 2 | |
| 3 | #include <inttypes.h> |
| 4 | #include <stdio.h> |
| 5 | #include <string.h> |
| 6 | |
| 7 | #include "aos/common/type_traits.h" |
| 8 | #include "aos/common/logging/logging.h" |
| 9 | |
| 10 | namespace aos { |
| 11 | |
| 12 | Mutex::Mutex() : impl_() { |
| 13 | static_assert(shm_ok<Mutex>::value, |
| 14 | "Mutex is not safe for use in shared memory."); |
| 15 | } |
| 16 | |
| 17 | Mutex::~Mutex() { |
Brian Silverman | 1dfe48b | 2014-09-06 16:13:02 -0400 | [diff] [blame^] | 18 | if (__builtin_expect(mutex_islocked(&impl_), false)) { |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 19 | LOG(FATAL, "destroying locked mutex %p (aka %p)\n", |
| 20 | this, &impl_); |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | // Lock and Unlock use the return values of mutex_lock/mutex_unlock |
| 25 | // to determine whether the lock/unlock succeeded. |
| 26 | |
| 27 | bool Mutex::Lock() { |
| 28 | const int ret = mutex_grab(&impl_); |
| 29 | if (ret == 0) { |
| 30 | return false; |
| 31 | } else { |
| 32 | LOG(FATAL, "mutex_grab(%p(=%" PRIu32 ")) failed with %d\n", |
| 33 | &impl_, impl_.futex, ret); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | void Mutex::Unlock() { |
| 38 | mutex_unlock(&impl_); |
| 39 | } |
| 40 | |
| 41 | Mutex::State Mutex::TryLock() { |
| 42 | const int ret = mutex_trylock(&impl_); |
| 43 | switch (ret) { |
| 44 | case 0: |
| 45 | return State::kLocked; |
| 46 | case 4: |
| 47 | return State::kUnlocked; |
| 48 | default: |
| 49 | LOG(FATAL, "mutex_trylock(%p(=%" PRIu32 ")) failed with %d\n", |
| 50 | &impl_, impl_.futex, ret); |
| 51 | } |
| 52 | } |
| 53 | |
Brian Silverman | 1dfe48b | 2014-09-06 16:13:02 -0400 | [diff] [blame^] | 54 | bool Mutex::OwnedBySelf() const { |
| 55 | return mutex_islocked(&impl_); |
| 56 | } |
| 57 | |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 58 | } // namespace aos |