blob: 5c5dcbe1b08d7354f5fcdb5f9a3b649568dc3daf [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#include "aos/mutex/mutex.h"
Brian Silvermandc1eb272014-08-19 14:25:59 -04002
Tyler Chatowbf0609c2021-07-31 16:13:27 -07003#include <cinttypes>
4#include <cstdio>
5#include <cstring>
Brian Silvermandc1eb272014-08-19 14:25:59 -04006
Alex Perrycb7da4b2019-08-28 19:35:56 -07007#include "glog/logging.h"
Brian Silvermandc1eb272014-08-19 14:25:59 -04008
Philipp Schrader790cb542023-07-05 21:06:52 -07009#include "aos/type_traits/type_traits.h"
10
Brian Silvermandc1eb272014-08-19 14:25:59 -040011namespace aos {
12
Brian Silvermandc1eb272014-08-19 14:25:59 -040013// Lock and Unlock use the return values of mutex_lock/mutex_unlock
14// to determine whether the lock/unlock succeeded.
15
16bool Mutex::Lock() {
17 const int ret = mutex_grab(&impl_);
18 if (ret == 0) {
19 return false;
Brian Silverman71c55c52014-08-19 14:31:59 -040020 } else if (ret == 1) {
21 return true;
Brian Silvermandc1eb272014-08-19 14:25:59 -040022 } else {
Alex Perrycb7da4b2019-08-28 19:35:56 -070023 LOG(FATAL) << "mutex_grab(" << &impl_ << "(=" << std::hex << impl_.futex
24 << ")) failed with " << ret;
Brian Silvermandc1eb272014-08-19 14:25:59 -040025 }
26}
27
Tyler Chatowbf0609c2021-07-31 16:13:27 -070028void Mutex::Unlock() { mutex_unlock(&impl_); }
Brian Silvermandc1eb272014-08-19 14:25:59 -040029
30Mutex::State Mutex::TryLock() {
31 const int ret = mutex_trylock(&impl_);
32 switch (ret) {
33 case 0:
34 return State::kLocked;
Brian Silverman71c55c52014-08-19 14:31:59 -040035 case 1:
36 return State::kOwnerDied;
Brian Silvermandc1eb272014-08-19 14:25:59 -040037 case 4:
Daniel Petti88a15662015-04-12 17:42:22 -040038 return State::kLockFailed;
Brian Silvermandc1eb272014-08-19 14:25:59 -040039 default:
Alex Perrycb7da4b2019-08-28 19:35:56 -070040 LOG(FATAL) << "mutex_trylock(" << &impl_ << "(=" << std::hex
41 << impl_.futex << ")) failed with " << ret;
Brian Silvermandc1eb272014-08-19 14:25:59 -040042 }
43}
44
Tyler Chatowbf0609c2021-07-31 16:13:27 -070045bool Mutex::OwnedBySelf() const { return mutex_islocked(&impl_); }
Brian Silverman1dfe48b2014-09-06 16:13:02 -040046
Brian Silvermandc1eb272014-08-19 14:25:59 -040047} // namespace aos