1 #ifndef MSP_CORE_MUTEX_H_
2 #define MSP_CORE_MUTEX_H_
4 #include "mspcore_api.h"
5 #include "noncopyable.h"
11 A class for controlling mutually exclusive access to a resource. Only one
12 thread can hold a lock on the mutex at a time.
14 class MSPCORE_API Mutex: private NonCopyable
16 friend class Semaphore;
21 Private *priv = nullptr;
27 /** Locks the mutex. If the mutex is already locked, waits until it becomes
31 /** Attempts to lock the mutex. Returns true if the lock was acquired,
32 otherwise returns false. */
35 /** Unlocks the mutex. */
40 Locks the mutex for the lifetime of the object.
42 class MSPCORE_API MutexLock
47 MutexLock(const MutexLock &);
49 MutexLock(Mutex &m, bool l = true): mutex(m) { if(l) mutex.lock(); }
50 ~MutexLock() { mutex.unlock(); }
52 void lock() { mutex.lock(); }
56 Protects a pointer with a mutex. As long as the MutexPtr (or a copy of it)
57 exists, the mutex will stay locked.
63 RefPtr<MutexLock> mutex;
67 MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
69 T &operator*() const { return *data; }
70 T *operator->() const { return data; }
71 void clear() { mutex = nullptr; data = nullptr; }