POSIX标准的Mutex互斥类

多个线程操作共享资源的时候总会存在冲突问题,唯一的解决办法就是引入互斥机制,好在Linux对此已提供了非常完美的支持。

CMutex.h

#pragma once

#ifndef WIN32
#include <pthread.h>
#else
#include <Windows.h>
#endif

class LockableObject
{
public:
	LockableObject(){}
	~LockableObject(){}

	virtual void lock() = 0;
	virtual void unlock() = 0;
};

class CCMutex: public LockableObject
{
public:
	CCMutex();
	~CCMutex();

	void lock();
	void unlock();

private:

#ifndef WIN32
	pthread_mutex_t  mutex_;
#else
	CRITICAL_SECTION  criticalSection_;
#endif
};

class MyGuard
{
public:
	MyGuard(LockableObject *pLockableObject)
	{
		pLockableObject_ = pLockableObject;
		pLockableObject_->lock();
	}

	~MyGuard()
	{
		pLockableObject_->unlock();
	}

private:
	LockableObject * pLockableObject_;
};

CMutex.cpp

#include "StdAfx.h"
#include "CMutex.h"

CCMutex::CCMutex()
{
#ifndef WIN32
	pthread_mutex_init(&mutex_, NULL);
#else
	InitializeCriticalSection(&criticalSection_);
#endif
}

CCMutex::~CCMutex()
{
#ifndef WIN32
	int ret = pthread_mutex_destroy(&mutex_);
#else
	DeleteCriticalSection(&criticalSection_);
#endif
}

void CCMutex::lock()
{
#ifndef WIN32
	int ret = pthread_mutex_lock(&mutex_);
#else
	EnterCriticalSection(&criticalSection_);
#endif
	return;
}

void CCMutex::unlock()
{
#ifndef WIN32
	int ret = pthread_mutex_unlock(&mutex_);
#else
	LeaveCriticalSection(&criticalSection_);
#endif
	return;
}