]> git.tdb.fi Git - libs/core.git/blob - source/core/mutex.h
Make Mutex non-copyable
[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         Mutex(const Mutex &);
22         Mutex &operator=(const Mutex &);
23 public:
24         Mutex();
25         ~Mutex();
26
27         /** Locks the mutex.  If the mutex is already locked, waits until it becomes
28         available. */
29         void lock();
30
31         /** Attempts to lock the mutex.  Returns true if the lock was acquired,
32         otherwise returns false. */
33         bool trylock();
34
35         /** Unlocks the mutex. */
36         void unlock();
37 };
38
39 /**
40 Locks the mutex for the lifetime of the object.
41 */
42 class MutexLock
43 {
44 private:
45         Mutex &mutex;
46
47         MutexLock(const MutexLock &);
48 public:
49         MutexLock(Mutex &m, bool l = true): mutex(m) { if(l) mutex.lock(); }
50         ~MutexLock() { mutex.unlock(); }
51
52         void lock() { mutex.lock(); }
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 private:
63         RefPtr<MutexLock> mutex;
64         T *data;
65
66 public:
67         MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
68
69         T &operator*() const { return *data; }
70         T *operator->() const { return data; }
71         void clear() { mutex = 0; data = 0; }
72 };
73
74 }
75
76 #endif