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 | |
| 8 | namespace aos { |
| 9 | |
| 10 | Mutex::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 | |
| 18 | Mutex::~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 | |
| 25 | void 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 | |
| 32 | void 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 | |
| 39 | bool 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 |