我想知道我实现通用互斥锁的方式是否是一种好的软件设计模式,它是线程安全的吗?
这是我的互斥锁类:
#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
}
这是它的使用方式:
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);
};
当我想使用 CEnvironment 时,我会执行以下操作:
env->Lock();
env->DoStuff(inData);
env->Unlock();