#ifndef GLTB_MUTEX_H #define GLTB_MUTEX_H #ifdef WIN32 #include #else #include "pthread.h" #endif #include "GLTB/referencedobject.h" #include "GLTB/refptr.h" namespace gltb { class Mutex : public ReferencedObject { private: Mutex() { #ifdef WIN32 InitializeCriticalSection(&criticalSection); #else pthread_mutexattr_t mutexAttributes; pthread_mutexattr_init(&mutexAttributes); pthread_mutexattr_settype(&mutexAttributes,PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex,&mutexAttributes); pthread_mutexattr_destroy(&mutexAttributes); #endif } public: virtual ~Mutex() { #ifdef WIN32 DeleteCriticalSection(&criticalSection); #else // force unlocking of mutex because // pthread_mutex_destroy requires that state pthread_mutex_unlock(&mutex); pthread_mutex_destroy(&mutex); #endif } void lock() { #ifdef WIN32 EnterCriticalSection(&criticalSection); #else pthread_mutex_lock(&mutex); #endif } void unlock() { #ifdef WIN32 LeaveCriticalSection(&criticalSection); #else pthread_mutex_unlock(&mutex); #endif } static RefPtr createMutex(); #ifdef WIN32 CRITICAL_SECTION *_getNative() { return &criticalSection; } #else pthread_mutex_t *_getNative() { return &mutex; } #endif private: #ifdef WIN32 CRITICAL_SECTION criticalSection; #else pthread_mutex_t mutex; #endif }; class MutexGuard { public: MutexGuard(RefPtr mutex) : mutex(mutex) { mutex->lock(); }; ~MutexGuard() { mutex->unlock(); }; private: RefPtr mutex; }; } #endif