blob: 35ac4e3bafcc4b5388c149c4539eeca031d8a1b6 [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#include "aos/common/mutex.h"
2
3#include <semLib.h>
4
5namespace aos {
6
7Mutex::Mutex() : impl_(semBCreate(SEM_Q_PRIORITY, SEM_FULL)) {
8 if (impl_ == NULL) {
9 LOG(FATAL,
10 "semBCreate(SEM_Q_PRIORITY, SEM_FULL) failed because of %d: %s\n",
11 errno, strerror(errno));
12 }
13}
14
15Mutex::~Mutex() {
16 if (semDelete(impl_) != 0) {
17 LOG(FATAL, "semDelete(%p) failed because of %d: %s\n",
18 impl_, errno, strerror(errno));
19 }
20}
21
22void Mutex::Lock() {
23 if (semTake(impl_, WAIT_FOREVER) != 0) {
24 LOG(FATAL, "semTake(%p, WAIT_FOREVER) failed because of %d: %s\n",
25 impl_, errno, strerror(errno));
26 }
27}
28
29void Mutex::Unlock() {
30 if (semGive(impl_) != 0) {
31 LOG(FATAL, "semGive(%p) failed because of %d: %s\n",
32 impl_, errno, strerror(errno));
33 }
34}
35
36bool Mutex::TryLock() {
37 if (semTake(impl_, NO_WAIT) == 0) {
38 return true;
39 }
40 // The semLib documention is wrong about what the errno will be.
41 if (errno != S_objLib_OBJ_UNAVAILABLE) {
42 LOG(FATAL, "semTake(%p, WAIT_FOREVER) failed because of %d: %s\n",
43 impl_, errno, strerror(errno));
44 }
45 return false;
46}
47
48} // namespace aos