]> git.tdb.fi Git - libs/core.git/blob - source/core/mutex.h
0fe9e82087ff67d4c51d1d7bcde0f2a10d668138
[libs/core.git] / source / core / mutex.h
1 #ifndef MSP_CORE_MUTEX_H_
2 #define MSP_CORE_MUTEX_H_
3
4 #include "refptr.h"
5
6 namespace Msp {
7
8 /**
9 A class for controlling mutually exclusive access to a resource.  Only one
10 thread can hold a lock on the mutex at a time.
11 */
12 class Mutex
13 {
14         friend class Semaphore;
15
16 private:
17         struct Private;
18
19         Private *priv;
20
21 public:
22         Mutex();
23         ~Mutex();
24
25         /** Locks the mutex.  If the mutex is already locked, waits until it becomes
26         available. */
27         void lock();
28
29         /** Attempts to lock the mutex.  Returns true if the lock was acquired,
30         otherwise returns false. */
31         bool trylock();
32
33         /** Unlocks the mutex. */
34         void unlock();
35 };
36
37 /**
38 Locks the mutex for the lifetime of the object.
39 */
40 class MutexLock
41 {
42 private:
43         Mutex &mutex;
44
45         MutexLock(const MutexLock &);
46 public:
47         MutexLock(Mutex &m, bool l = true): mutex(m) { if(l) mutex.lock(); }
48         ~MutexLock() { mutex.unlock(); }
49
50         void lock() { mutex.lock(); }
51 };
52
53 /**
54 Protects a pointer with a mutex.  As long as the MutexPtr (or a copy of it)
55 exists, the mutex will stay locked.
56 */
57 template<typename T>
58 class MutexPtr
59 {
60 private:
61         RefPtr<MutexLock> mutex;
62         T *data;
63
64 public:
65         MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
66
67         T &operator*() const { return *data; }
68         T *operator->() const { return data; }
69         void clear() { mutex = 0; data = 0; }
70 };
71
72 }
73
74 #endif