blob: e8951c6200dff0eea84635246c56a142221cc329 [file] [log] [blame]
Brian Silvermandc1eb272014-08-19 14:25:59 -04001#include "aos/common/mutex.h"
2
3#include <inttypes.h>
4#include <stdio.h>
5#include <string.h>
6
7#include "aos/common/type_traits.h"
8#include "aos/common/logging/logging.h"
9
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 {
22 LOG(FATAL, "mutex_grab(%p(=%" PRIu32 ")) failed with %d\n",
23 &impl_, impl_.futex, ret);
24 }
25}
26
27void Mutex::Unlock() {
28 mutex_unlock(&impl_);
29}
30
31Mutex::State Mutex::TryLock() {
32 const int ret = mutex_trylock(&impl_);
33 switch (ret) {
34 case 0:
35 return State::kLocked;
Brian Silverman71c55c52014-08-19 14:31:59 -040036 case 1:
37 return State::kOwnerDied;
Brian Silvermandc1eb272014-08-19 14:25:59 -040038 case 4:
Daniel Petti88a15662015-04-12 17:42:22 -040039 return State::kLockFailed;
Brian Silvermandc1eb272014-08-19 14:25:59 -040040 default:
41 LOG(FATAL, "mutex_trylock(%p(=%" PRIu32 ")) failed with %d\n",
42 &impl_, impl_.futex, ret);
43 }
44}
45
Brian Silverman1dfe48b2014-09-06 16:13:02 -040046bool Mutex::OwnedBySelf() const {
47 return mutex_islocked(&impl_);
48}
49
Brian Silvermandc1eb272014-08-19 14:25:59 -040050} // namespace aos