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_
18 friend class Semaphore;
25 Mutex() { pthread_mutex_init(&mutex, 0); }
26 int lock() { return pthread_mutex_lock(&mutex); }
27 int trylock() { return pthread_mutex_trylock(&mutex); }
28 int unlock() { return pthread_mutex_unlock(&mutex); }
29 ~Mutex() { pthread_mutex_destroy(&mutex); }
31 Mutex() { mutex=CreateMutex(0, false, 0); }
32 int lock() { return WaitForSingleObject(mutex, INFINITE)==WAIT_OBJECT_0; }
33 int trylock() { return WaitForSingleObject(mutex, 0)==WAIT_OBJECT_0; }
34 int unlock() { return !ReleaseMutex(mutex); }
35 ~Mutex() { CloseHandle(mutex); }
40 Locks the mutex for te lifetime of the object.
48 MutexLock(Mutex &m, bool l=true): mutex(m) { if(l) mutex.lock(); }
49 ~MutexLock() { mutex.unlock(); }
51 int lock() { return mutex.lock(); }
53 MutexLock(const MutexLock &);
54 MutexLock &operator=(const MutexLock &);
58 Protects a pointer with a mutex. As long as the MutexPtr (or a copy of it)
59 exists, the mutex will stay locked.
65 MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
67 T &operator*() const { return *data; }
68 T *operator->() const { return data; }
69 void clear() { mutex=0; data=0; }
71 RefPtr<MutexLock> mutex;
75 /*template<typename T>
76 class MutexPtr: public RefCount
79 MutexPtr(T *d, Mutex &m): mutex(m), data(d) { mutex.lock(); }
80 MutexPtr(const MutexPtr<T> &p): RefCount(p), mutex(p.mutex), data(p.data) { }
81 T &operator*() const { return *data; }
82 T *operator->() const { return data; }
83 void clear() { decref(); data=0; }
84 ~MutexPtr() { decref(); }
91 if(!RefCount::decref())