1 /* 2 * Copyright 2009, Michael Lotz, mmlr@mlotz.ch. 3 * Distributed under the terms of the MIT License. 4 */ 5 #ifndef _LOCKS_H_ 6 #define _LOCKS_H_ 7 8 #include <OS.h> 9 10 #ifdef __cplusplus 11 extern "C" { 12 #endif 13 14 typedef struct mutex { 15 int32 benaphore; 16 sem_id semaphore; 17 } mutex; 18 19 status_t mutex_init(mutex *lock, const char *name); 20 void mutex_destroy(mutex *lock); 21 status_t mutex_lock(mutex *lock); 22 void mutex_unlock(mutex *lock); 23 24 25 typedef struct rw_lock { 26 const char * name; 27 mutex lock; 28 struct rw_lock_waiter * waiters; 29 struct rw_lock_waiter * last_waiter; 30 thread_id holder; 31 int32 reader_count; 32 int32 writer_count; 33 int32 owner_count; 34 } rw_lock; 35 36 status_t rw_lock_init(rw_lock *lock, const char *name); 37 void rw_lock_destroy(rw_lock *lock); 38 status_t rw_lock_read_lock(rw_lock *lock); 39 status_t rw_lock_read_unlock(rw_lock *lock); 40 status_t rw_lock_write_lock(rw_lock *lock); 41 status_t rw_lock_write_unlock(rw_lock *lock); 42 43 #ifdef __cplusplus 44 } // extern "C" 45 46 47 #include <AutoLocker.h> 48 49 class MutexLocking { 50 public: 51 inline bool Lock(struct mutex *lock) 52 { 53 return mutex_lock(lock) == B_OK; 54 } 55 56 inline void Unlock(struct mutex *lock) 57 { 58 mutex_unlock(lock); 59 } 60 }; 61 62 63 class RWLockReadLocking { 64 public: 65 inline bool Lock(struct rw_lock *lock) 66 { 67 return rw_lock_read_lock(lock) == B_OK; 68 } 69 70 inline void Unlock(struct rw_lock *lock) 71 { 72 rw_lock_read_unlock(lock); 73 } 74 }; 75 76 77 class RWLockWriteLocking { 78 public: 79 inline bool Lock(struct rw_lock *lock) 80 { 81 return rw_lock_write_lock(lock) == B_OK; 82 } 83 84 inline void Unlock(struct rw_lock *lock) 85 { 86 rw_lock_write_unlock(lock); 87 } 88 }; 89 90 91 typedef AutoLocker<mutex, MutexLocking> MutexLocker; 92 typedef AutoLocker<rw_lock, RWLockReadLocking> ReadLocker; 93 typedef AutoLocker<rw_lock, RWLockWriteLocking> WriteLocker; 94 95 #endif // __cplusplus 96 97 #endif // _LOCKS_H_ 98