John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 1 | #include "aos/mutex/mutex.h" |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 2 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 3 | #include "glog/logging.h" |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 4 | |
| 5 | namespace aos { |
| 6 | |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 7 | // Lock and Unlock use the return values of mutex_lock/mutex_unlock |
| 8 | // to determine whether the lock/unlock succeeded. |
| 9 | |
| 10 | bool Mutex::Lock() { |
| 11 | const int ret = mutex_grab(&impl_); |
| 12 | if (ret == 0) { |
| 13 | return false; |
Brian Silverman | 71c55c5 | 2014-08-19 14:31:59 -0400 | [diff] [blame] | 14 | } else if (ret == 1) { |
| 15 | return true; |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 16 | } else { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 17 | LOG(FATAL) << "mutex_grab(" << &impl_ << "(=" << std::hex << impl_.futex |
| 18 | << ")) failed with " << ret; |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 19 | } |
| 20 | } |
| 21 | |
Tyler Chatow | bf0609c | 2021-07-31 16:13:27 -0700 | [diff] [blame] | 22 | void Mutex::Unlock() { mutex_unlock(&impl_); } |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 23 | |
| 24 | Mutex::State Mutex::TryLock() { |
| 25 | const int ret = mutex_trylock(&impl_); |
| 26 | switch (ret) { |
| 27 | case 0: |
| 28 | return State::kLocked; |
Brian Silverman | 71c55c5 | 2014-08-19 14:31:59 -0400 | [diff] [blame] | 29 | case 1: |
| 30 | return State::kOwnerDied; |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 31 | case 4: |
Daniel Petti | 88a1566 | 2015-04-12 17:42:22 -0400 | [diff] [blame] | 32 | return State::kLockFailed; |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 33 | default: |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 34 | LOG(FATAL) << "mutex_trylock(" << &impl_ << "(=" << std::hex |
| 35 | << impl_.futex << ")) failed with " << ret; |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 36 | } |
| 37 | } |
| 38 | |
Tyler Chatow | bf0609c | 2021-07-31 16:13:27 -0700 | [diff] [blame] | 39 | bool Mutex::OwnedBySelf() const { return mutex_islocked(&impl_); } |
Brian Silverman | 1dfe48b | 2014-09-06 16:13:02 -0400 | [diff] [blame] | 40 | |
Brian Silverman | dc1eb27 | 2014-08-19 14:25:59 -0400 | [diff] [blame] | 41 | } // namespace aos |