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