1 #ifndef MSP_CORE_MUTEX_H_
2 #define MSP_CORE_MUTEX_H_
4 #include "noncopyable.h"
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.
13 class Mutex: private NonCopyable
15 friend class Semaphore;
20 Private *priv = nullptr;
26 /** Locks the mutex. If the mutex is already locked, waits until it becomes
30 /** Attempts to lock the mutex. Returns true if the lock was acquired,
31 otherwise returns false. */
34 /** Unlocks the mutex. */
39 Locks the mutex for the lifetime of the object.
46 MutexLock(const MutexLock &);
48 MutexLock(Mutex &m, bool l = true): mutex(m) { if(l) mutex.lock(); }
49 ~MutexLock() { mutex.unlock(); }
51 void lock() { mutex.lock(); }
55 Protects a pointer with a mutex. As long as the MutexPtr (or a copy of it)
56 exists, the mutex will stay locked.
62 RefPtr<MutexLock> mutex;
66 MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
68 T &operator*() const { return *data; }
69 T *operator->() const { return data; }
70 void clear() { mutex = nullptr; data = nullptr; }