blob: 30a9534a77b9483e0a4a3974bc81e0da87b78fb7 [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#include "aos/mutex/mutex.h"
Brian Silvermandc1eb272014-08-19 14:25:59 -04002
Alex Perrycb7da4b2019-08-28 19:35:56 -07003#include "glog/logging.h"
Brian Silvermandc1eb272014-08-19 14:25:59 -04004
5namespace aos {
6
Brian Silvermandc1eb272014-08-19 14:25:59 -04007// Lock and Unlock use the return values of mutex_lock/mutex_unlock
8// to determine whether the lock/unlock succeeded.
9
10bool Mutex::Lock() {
11 const int ret = mutex_grab(&impl_);
12 if (ret == 0) {
13 return false;
Brian Silverman71c55c52014-08-19 14:31:59 -040014 } else if (ret == 1) {
15 return true;
Brian Silvermandc1eb272014-08-19 14:25:59 -040016 } else {
Alex Perrycb7da4b2019-08-28 19:35:56 -070017 LOG(FATAL) << "mutex_grab(" << &impl_ << "(=" << std::hex << impl_.futex
18 << ")) failed with " << ret;
Brian Silvermandc1eb272014-08-19 14:25:59 -040019 }
20}
21
Tyler Chatowbf0609c2021-07-31 16:13:27 -070022void Mutex::Unlock() { mutex_unlock(&impl_); }
Brian Silvermandc1eb272014-08-19 14:25:59 -040023
24Mutex::State Mutex::TryLock() {
25 const int ret = mutex_trylock(&impl_);
26 switch (ret) {
27 case 0:
28 return State::kLocked;
Brian Silverman71c55c52014-08-19 14:31:59 -040029 case 1:
30 return State::kOwnerDied;
Brian Silvermandc1eb272014-08-19 14:25:59 -040031 case 4:
Daniel Petti88a15662015-04-12 17:42:22 -040032 return State::kLockFailed;
Brian Silvermandc1eb272014-08-19 14:25:59 -040033 default:
Alex Perrycb7da4b2019-08-28 19:35:56 -070034 LOG(FATAL) << "mutex_trylock(" << &impl_ << "(=" << std::hex
35 << impl_.futex << ")) failed with " << ret;
Brian Silvermandc1eb272014-08-19 14:25:59 -040036 }
37}
38
Tyler Chatowbf0609c2021-07-31 16:13:27 -070039bool Mutex::OwnedBySelf() const { return mutex_islocked(&impl_); }
Brian Silverman1dfe48b2014-09-06 16:13:02 -040040
Brian Silvermandc1eb272014-08-19 14:25:59 -040041} // namespace aos