I'm wondering if my way of implementing a generic mutex is a good software design pattern, and is it thread safe?
Here is my mutex class:
#ifdef HAVE_WINDOWS_H
void *CSimpleMutex::object;
#endif
#ifdef _PTHREADS
pthread_mutex_t CSimpleMutex::object;
#endif
CSimpleMutex::CSimpleMutex(bool lockable)
{
isLockableMutex = lockable;
if (!lockable)
{
#ifdef _WINDOWS
object = CreateMutex(NULL, false, NULL);
#endif
#ifdef _PTHREADS
pthread_mutex_init(&object, NULL);
#endif
}
else
{
#ifdef _WINDOWS
InitializeCriticalSection(&mutex);
#endif
#ifdef _PTHREADS
pthread_mutex_init(&mutex, NULL);
#endif
}
}
CSimpleMutex::~CSimpleMutex()
{
if (!isLockableMutex)
{
#ifdef _WINDOWS
if(object!=NULL)
{
CloseHandle(object);
}
#endif
#ifdef _PTHREADS
pthread_mutex_destroy(&object);
#endif
}
else
{
#ifdef _WINDOWS
DeleteCriticalSection(&mutex);
#endif
#ifdef _PTHREADS
pthread_mutex_destroy(&mutex);
#endif
}
}
// Aquires a lock
void CSimpleMutex::Lock()
{
if (!isLockableMutex)
return;
#ifdef _WINDOWS
EnterCriticalSection(&mutex);
#endif
#ifdef _PTHREADS
pthread_mutex_lock(&mutex);
#endif
}
// Releases a lock
void CSimpleMutex::Unlock()
{
if (!isLockableMutex)
return;
#ifdef _WINDOWS
LeaveCriticalSection(&mutex);
#endif
#ifdef _PTHREADS
pthread_mutex_unlock(&mutex);
#endif
}
This is how it is used:
class CEnvironment : public CHandleBase
{
private:
CSimpleMutex *mutex;
public:
CEnvironment(){mutex = new CSimpleMutex(true);};
~CEnvironment(){delete mutex;};
void Lock() { mutex->Lock(); };
void Unlock() { mutex->Unlock(); };
void DoStuff(void *data);
};
When I want to use CEnvironment I do something like this:
env->Lock();
env->DoStuff(inData);
env->Unlock();