]> git.tdb.fi Git - libs/core.git/blob - source/core/mutex.h
Refactor Mutex with pimpl
[libs/core.git] / source / core / mutex.h
1 /* $Id$
2
3 This file is part of libmspcore
4 Copyright © 2006 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #ifndef MSP_CORE_MUTEX_H_
9 #define MSP_CORE_MUTEX_H_
10
11 #include "refptr.h"
12
13 namespace Msp {
14
15 /**
16 A class for controlling mutually exclusive access to a resource.  Only one
17 thread can hold a lock on the mutex at a time.
18 */
19 class Mutex
20 {
21         friend class Semaphore;
22
23 private:
24         struct Private;
25
26         Private *priv;
27
28 public:
29         Mutex();
30         ~Mutex();
31
32         /** Locks the mutex.  If the mutex is already locked, waits until it becomes
33         available. */
34         void lock();
35
36         /** Attempts to lock the mutex.  Returns true if the lock was acquired,
37         otherwise returns false. */
38         bool trylock();
39
40         /** Unlocks the mutex. */
41         void unlock();
42 };
43
44 /**
45 Locks the mutex for te lifetime of the object.
46 */
47 class MutexLock
48 {
49 private:
50         Mutex &mutex;
51
52 public:
53         MutexLock(Mutex &m, bool l = true): mutex(m) { if(l) mutex.lock(); }
54         ~MutexLock() { mutex.unlock(); }
55
56         void lock() { mutex.lock(); }
57 private:
58         MutexLock(const MutexLock &);
59         MutexLock &operator=(const MutexLock &);
60 };
61
62 /**
63 Protects a pointer with a mutex.  As long as the MutexPtr (or a copy of it)
64 exists, the mutex will stay locked.
65 */
66 template<typename T>
67 class MutexPtr
68 {
69 public:
70         MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
71
72         T &operator*() const { return *data; }
73         T *operator->() const { return data; }
74         void clear() { mutex=0; data = 0; }
75 private:
76         RefPtr<MutexLock> mutex;
77         T *data;
78 };
79
80 /*template<typename T>
81 class MutexPtr: public RefCount
82 {
83 public:
84         MutexPtr(T *d, Mutex &m): mutex(m), data(d) { mutex.lock(); }
85         MutexPtr(const MutexPtr<T> &p): RefCount(p), mutex(p.mutex), data(p.data) { }
86         T &operator*() const { return *data; }
87         T *operator->() const { return data; }
88         void clear() { decref(); data = 0; }
89         ~MutexPtr() { decref(); }
90 protected:
91         Mutex &mutex;
92         T     *data;
93
94         bool decref()
95         {
96                 if(!RefCount::decref())
97                 {
98                         mutex.unlock();
99                         return false;
100                 }
101                 return true;
102         }
103 };*/
104
105 }
106
107 #endif