brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame^] | 1 | #include "aos/common/mutex.h" |
| 2 | |
| 3 | #include <semLib.h> |
| 4 | |
| 5 | namespace aos { |
| 6 | |
| 7 | Mutex::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 | |
| 15 | Mutex::~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 | |
| 22 | void 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 | |
| 29 | void 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 | |
| 36 | bool 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 |