3 This file is part of libmspcore
4 Copyright © 2006 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
7 #ifndef MSP_CORE_MUTEX_H_
8 #define MSP_CORE_MUTEX_H_
19 Mutex() { pthread_mutex_init(&mutex, 0); }
20 int lock() { return pthread_mutex_lock(&mutex); }
21 int trylock() { return pthread_mutex_trylock(&mutex); }
22 int unlock() { return pthread_mutex_unlock(&mutex); }
23 ~Mutex() { pthread_mutex_destroy(&mutex); }
25 Mutex() { mutex=CreateMutex(0, false, 0); }
26 int lock() { return WaitForSingleObject(mutex, INFINITE)==WAIT_OBJECT_0; }
27 int trylock() { return WaitForSingleObject(mutex, 0)==WAIT_OBJECT_0; }
28 int unlock() { return !ReleaseMutex(mutex); }
29 ~Mutex() { CloseHandle(mutex); }
34 friend class Semaphore;
38 Locks the mutex for te lifetime of the object.
43 MutexLock(Mutex &m, bool l=true): mutex(m) { if(l) mutex.lock(); }
44 ~MutexLock() { mutex.unlock(); }
46 int lock() { return mutex.lock(); }
50 MutexLock(const MutexLock &);
51 MutexLock &operator=(const MutexLock &);
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 MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { }
64 T &operator*() const { return *data; }
65 T *operator->() const { return data; }
66 void clear() { mutex=0; data=0; }
68 RefPtr<MutexLock> mutex;
72 /*template<typename T>
73 class MutexPtr: public RefCount
76 MutexPtr(T *d, Mutex &m): mutex(m), data(d) { mutex.lock(); }
77 MutexPtr(const MutexPtr<T> &p): RefCount(p), mutex(p.mutex), data(p.data) { }
78 T &operator*() const { return *data; }
79 T *operator->() const { return data; }
80 void clear() { decref(); data=0; }
81 ~MutexPtr() { decref(); }
88 if(!RefCount::decref())