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