]> git.tdb.fi Git - libs/core.git/blob - source/core/mutex.h
Remove the old commented out MutexPtr implementation
[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 te lifetime of the object.
39 */
40 class MutexLock
41 {
42 private:
43         Mutex &mutex;
44
45 public:
46         MutexLock(Mutex &m, bool l = true): mutex(m) { if(l) mutex.lock(); }
47         ~MutexLock() { mutex.unlock(); }
48
49         void lock() { mutex.lock(); }
50 private:
51         MutexLock(const MutexLock &);
52         MutexLock &operator=(const MutexLock &);
53 };
54
55 /**
56 Protects a pointer with a mutex.  As long as the MutexPtr (or a copy of it)
57 exists, the mutex will stay locked.
58 */
59 template<typename T>
60 class MutexPtr
61 {
62 public:
63         MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
64
65         T &operator*() const { return *data; }
66         T *operator->() const { return data; }
67         void clear() { mutex=0; data = 0; }
68 private:
69         RefPtr<MutexLock> mutex;
70         T *data;
71 };
72
73 }
74
75 #endif