diff options
author | Vegard Storheil Eriksen <zyp@jvnv.net> | 2011-10-10 00:17:23 +0200 |
---|---|---|
committer | Vegard Storheil Eriksen <zyp@jvnv.net> | 2011-10-10 00:17:23 +0200 |
commit | 9a2a640c575ade2a4589e1954271abe3ed1e3f79 (patch) | |
tree | 89969b674d25441ba216c2601fe6137e2b823cdf | |
parent | c6e20fda3ec5ea0c177455a6922da80b96856d81 (diff) |
Add mutex class.
-rw-r--r-- | mutex.h | 42 |
1 files changed, 42 insertions, 0 deletions
@@ -0,0 +1,42 @@ +#ifndef MUTEX_H +#define MUTEX_H + +class Mutex { + private: + uint8_t locked; + public: + Mutex() : locked(0) {} + Mutex(uint8_t l) : locked(l) {} + + bool trylock() { + uint8_t val; + + // Check if mutex is locked. + asm volatile ("ldrexb %0, [%1]" : "=r" (val) : "r" (&locked)); + if(val) { + return false; + } + + // Try taking the lock. + asm volatile ("strexb %0, %1, [%2]" : "=r" (val) : "r" (1), "r" (&locked)); + if(val) { + return false; + } + + asm volatile("dmb"); + return true; + } + + void lock() { + while(!trylock()) { + Thread::yield(); + } + } + + void unlock() { + asm volatile("dmb"); + locked = 0; + } +}; + +#endif |