blob: 18d233d7974a747c8069ef7e8575cf68e7421918 [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
John Park33858a32018-09-28 23:05:48 -07007#include "aos/type_traits/type_traits.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include "glog/logging.h"
Brian Silvermandc1eb272014-08-19 14:25:59 -04009
10namespace aos {
11
Brian Silvermandc1eb272014-08-19 14:25:59 -040012// Lock and Unlock use the return values of mutex_lock/mutex_unlock
13// to determine whether the lock/unlock succeeded.
14
15bool Mutex::Lock() {
16 const int ret = mutex_grab(&impl_);
17 if (ret == 0) {
18 return false;
Brian Silverman71c55c52014-08-19 14:31:59 -040019 } else if (ret == 1) {
20 return true;
Brian Silvermandc1eb272014-08-19 14:25:59 -040021 } else {
Alex Perrycb7da4b2019-08-28 19:35:56 -070022 LOG(FATAL) << "mutex_grab(" << &impl_ << "(=" << std::hex << impl_.futex
23 << ")) failed with " << ret;
Brian Silvermandc1eb272014-08-19 14:25:59 -040024 }
25}
26
Tyler Chatowbf0609c2021-07-31 16:13:27 -070027void Mutex::Unlock() { mutex_unlock(&impl_); }
Brian Silvermandc1eb272014-08-19 14:25:59 -040028
29Mutex::State Mutex::TryLock() {
30 const int ret = mutex_trylock(&impl_);
31 switch (ret) {
32 case 0:
33 return State::kLocked;
Brian Silverman71c55c52014-08-19 14:31:59 -040034 case 1:
35 return State::kOwnerDied;
Brian Silvermandc1eb272014-08-19 14:25:59 -040036 case 4:
Daniel Petti88a15662015-04-12 17:42:22 -040037 return State::kLockFailed;
Brian Silvermandc1eb272014-08-19 14:25:59 -040038 default:
Alex Perrycb7da4b2019-08-28 19:35:56 -070039 LOG(FATAL) << "mutex_trylock(" << &impl_ << "(=" << std::hex
40 << impl_.futex << ")) failed with " << ret;
Brian Silvermandc1eb272014-08-19 14:25:59 -040041 }
42}
43
Tyler Chatowbf0609c2021-07-31 16:13:27 -070044bool Mutex::OwnedBySelf() const { return mutex_islocked(&impl_); }
Brian Silverman1dfe48b2014-09-06 16:13:02 -040045
Brian Silvermandc1eb272014-08-19 14:25:59 -040046} // namespace aos