blob: c5b86528075dc55b48c1a2b2a8341856c7883551 [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
12Mutex::Mutex() : impl_() {
13 static_assert(shm_ok<Mutex>::value,
14 "Mutex is not safe for use in shared memory.");
15}
16
17Mutex::~Mutex() {
Brian Silverman1dfe48b2014-09-06 16:13:02 -040018 if (__builtin_expect(mutex_islocked(&impl_), false)) {
Brian Silvermandc1eb272014-08-19 14:25:59 -040019 LOG(FATAL, "destroying locked mutex %p (aka %p)\n",
20 this, &impl_);
21 }
22}
23
24// Lock and Unlock use the return values of mutex_lock/mutex_unlock
25// to determine whether the lock/unlock succeeded.
26
27bool Mutex::Lock() {
28 const int ret = mutex_grab(&impl_);
29 if (ret == 0) {
30 return false;
31 } else {
32 LOG(FATAL, "mutex_grab(%p(=%" PRIu32 ")) failed with %d\n",
33 &impl_, impl_.futex, ret);
34 }
35}
36
37void Mutex::Unlock() {
38 mutex_unlock(&impl_);
39}
40
41Mutex::State Mutex::TryLock() {
42 const int ret = mutex_trylock(&impl_);
43 switch (ret) {
44 case 0:
45 return State::kLocked;
46 case 4:
Daniel Petti88a15662015-04-12 17:42:22 -040047 return State::kLockFailed;
Brian Silvermandc1eb272014-08-19 14:25:59 -040048 default:
49 LOG(FATAL, "mutex_trylock(%p(=%" PRIu32 ")) failed with %d\n",
50 &impl_, impl_.futex, ret);
51 }
52}
53
Brian Silverman1dfe48b2014-09-06 16:13:02 -040054bool Mutex::OwnedBySelf() const {
55 return mutex_islocked(&impl_);
56}
57
Brian Silvermandc1eb272014-08-19 14:25:59 -040058} // namespace aos