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