blob: 4a3fb25d14dbb0329996de596b5be6beabc4989d [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#include "aos/mutex/mutex.h"
Brian Silvermandc1eb272014-08-19 14:25:59 -04002
Austin Schuh99f7c6a2024-06-25 22:07:44 -07003#include "absl/log/check.h"
4#include "absl/log/log.h"
Brian Silvermandc1eb272014-08-19 14:25:59 -04005
6namespace aos {
7
Brian Silvermandc1eb272014-08-19 14:25:59 -04008// Lock and Unlock use the return values of mutex_lock/mutex_unlock
9// to determine whether the lock/unlock succeeded.
10
11bool Mutex::Lock() {
12 const int ret = mutex_grab(&impl_);
13 if (ret == 0) {
14 return false;
Brian Silverman71c55c52014-08-19 14:31:59 -040015 } else if (ret == 1) {
16 return true;
Brian Silvermandc1eb272014-08-19 14:25:59 -040017 } else {
Alex Perrycb7da4b2019-08-28 19:35:56 -070018 LOG(FATAL) << "mutex_grab(" << &impl_ << "(=" << std::hex << impl_.futex
19 << ")) failed with " << ret;
Brian Silvermandc1eb272014-08-19 14:25:59 -040020 }
21}
22
Tyler Chatowbf0609c2021-07-31 16:13:27 -070023void Mutex::Unlock() { mutex_unlock(&impl_); }
Brian Silvermandc1eb272014-08-19 14:25:59 -040024
25Mutex::State Mutex::TryLock() {
26 const int ret = mutex_trylock(&impl_);
27 switch (ret) {
28 case 0:
29 return State::kLocked;
Brian Silverman71c55c52014-08-19 14:31:59 -040030 case 1:
31 return State::kOwnerDied;
Brian Silvermandc1eb272014-08-19 14:25:59 -040032 case 4:
Daniel Petti88a15662015-04-12 17:42:22 -040033 return State::kLockFailed;
Brian Silvermandc1eb272014-08-19 14:25:59 -040034 default:
Alex Perrycb7da4b2019-08-28 19:35:56 -070035 LOG(FATAL) << "mutex_trylock(" << &impl_ << "(=" << std::hex
36 << impl_.futex << ")) failed with " << ret;
Brian Silvermandc1eb272014-08-19 14:25:59 -040037 }
38}
39
Tyler Chatowbf0609c2021-07-31 16:13:27 -070040bool Mutex::OwnedBySelf() const { return mutex_islocked(&impl_); }
Brian Silverman1dfe48b2014-09-06 16:13:02 -040041
Brian Silvermandc1eb272014-08-19 14:25:59 -040042} // namespace aos