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 | |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 12 | // Lock and Unlock use the return values of mutex_lock/mutex_unlock |
| 13 | // to determine whether the lock/unlock succeeded. |
| 14 | |
| 15 | bool Mutex::Lock() { |
| 16 | const int ret = mutex_grab(&impl_); |
| 17 | if (ret == 0) { |
| 18 | return false; |
Brian Silverman | 71c55c5 | 2014-08-19 14:31:59 -0400 | [diff] [blame] | 19 | } else if (ret == 1) { |
| 20 | return true; |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 21 | } else { |
| 22 | LOG(FATAL, "mutex_grab(%p(=%" PRIu32 ")) failed with %d\n", |
| 23 | &impl_, impl_.futex, ret); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | void Mutex::Unlock() { |
| 28 | mutex_unlock(&impl_); |
| 29 | } |
| 30 | |
| 31 | Mutex::State Mutex::TryLock() { |
| 32 | const int ret = mutex_trylock(&impl_); |
| 33 | switch (ret) { |
| 34 | case 0: |
| 35 | return State::kLocked; |
Brian Silverman | 71c55c5 | 2014-08-19 14:31:59 -0400 | [diff] [blame] | 36 | case 1: |
| 37 | return State::kOwnerDied; |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 38 | case 4: |
Daniel Petti | 88a1566 | 2015-04-12 17:42:22 -0400 | [diff] [blame] | 39 | return State::kLockFailed; |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 40 | default: |
| 41 | LOG(FATAL, "mutex_trylock(%p(=%" PRIu32 ")) failed with %d\n", |
| 42 | &impl_, impl_.futex, ret); |
| 43 | } |
| 44 | } |
| 45 | |
Brian Silverman | 1dfe48b | 2014-09-06 16:13:02 -0400 | [diff] [blame] | 46 | bool Mutex::OwnedBySelf() const { |
| 47 | return mutex_islocked(&impl_); |
| 48 | } |
| 49 | |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 50 | } // namespace aos |