brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 1 | #include "aos/common/mutex.h" |
| 2 | |
| 3 | #include <semLib.h> |
Brian Silverman | f665d69 | 2013-02-17 22:11:39 -0800 | [diff] [blame] | 4 | #include <string.h> |
| 5 | |
| 6 | #include "aos/common/logging/logging.h" |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 7 | |
Brian Silverman | 4926dd0 | 2013-02-28 16:03:41 -0800 | [diff] [blame] | 8 | #include "aos/common/logging/logging.h" |
| 9 | |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 10 | namespace aos { |
| 11 | |
| 12 | Mutex::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 | |
| 20 | Mutex::~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 | |
| 27 | void 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 | |
| 34 | void 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 | |
| 41 | bool 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 |