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