3 This file is part of libmspcore
4 Copyright © 2006 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
8 #ifndef MSP_CORE_MUTEX_H_
9 #define MSP_CORE_MUTEX_H_
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.
21 friend class Semaphore;
32 /** Locks the mutex. If the mutex is already locked, waits until it becomes
36 /** Attempts to lock the mutex. Returns true if the lock was acquired,
37 otherwise returns false. */
40 /** Unlocks the mutex. */
45 Locks the mutex for te lifetime of the object.
53 MutexLock(Mutex &m, bool l = true): mutex(m) { if(l) mutex.lock(); }
54 ~MutexLock() { mutex.unlock(); }
56 void lock() { mutex.lock(); }
58 MutexLock(const MutexLock &);
59 MutexLock &operator=(const MutexLock &);
63 Protects a pointer with a mutex. As long as the MutexPtr (or a copy of it)
64 exists, the mutex will stay locked.
70 MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
72 T &operator*() const { return *data; }
73 T *operator->() const { return data; }
74 void clear() { mutex=0; data = 0; }
76 RefPtr<MutexLock> mutex;
80 /*template<typename T>
81 class MutexPtr: public RefCount
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(); }
96 if(!RefCount::decref())