2 This file is part of libmspframework
3 Copyright © 2006 Mikko Rasa, Mikkosoft Productions
4 Distributed under the LGPL
6 #ifndef MSP_FRAMEWORK_MUTEX_H_
7 #define MSP_FRAMEWORK_MUTEX_H_
9 #include <msp/refcount.h>
18 Mutex() { pthread_mutex_init(&mutex, 0); }
19 int lock() { return pthread_mutex_lock(&mutex); }
20 int trylock() { return pthread_mutex_trylock(&mutex); }
21 int unlock() { return pthread_mutex_unlock(&mutex); }
22 ~Mutex() { pthread_mutex_destroy(&mutex); }
24 Mutex() { mutex=CreateMutex(0, false, 0); }
25 int lock() { return WaitForSingleObject(mutex, INFINITE)==WAIT_OBJECT_0; }
26 int trylock() { return WaitForSingleObject(mutex, 0)==WAIT_OBJECT_0; }
27 int unlock() { return !ReleaseMutex(mutex); }
28 ~Mutex() { CloseHandle(mutex); }
33 friend class Semaphore;
39 MutexLock(Mutex &m): mutex(m) { mutex.lock(); }
40 ~MutexLock() { mutex.unlock(); }
47 class MutexPtr: public RefCount
50 MutexPtr(T *d, Mutex &m): mutex(m), data(d) { mutex.lock(); }
51 MutexPtr(const MutexPtr<T> &p): RefCount(p), mutex(p.mutex), data(p.data) { }
52 T &operator*() const { return *data; }
53 T *operator->() const { return data; }
54 void clear() { decref(); data=0; }
55 ~MutexPtr() { decref(); }
62 if(!RefCount::decref())