Linux平台用C++封装线程读写锁

    在Linux平台上已经有现成的线程读写锁pthread_rwlock_t以及相关API,现将这些API封装成与Win32平台上相同的接口,以便于编写跨平台程序。这些API包括pthread_rwlock_init,pthread_rwlock_rdlock,pthread_rwlock_tryrdlock,pthread_rwlock_wrlock,pthread_rwlock_trywrlock,pthread_rwlock_unlock,pthread_rwlock_destroy,可在Linux在线手册上查阅它们的说明。下边的代码在VS2005中编辑,在Fedora 13虚拟机中编译,测试通过。

RWLockImpl.h

#ifndef _RWLockImpl_Header
#define _RWLockImpl_Header

#include 
#include 
#include 
#include 

using namespace std;

/*
 读写锁允许当前的多个读用户访问保护资源,但只允许一个写读者访问保护资源
*/

//-----------------------------------------------------------------
class CRWLockImpl
{
protected:
	CRWLockImpl();
	~CRWLockImpl();
	void ReadLockImpl();
	bool TryReadLockImpl();
	void WriteLockImpl();
	bool TryWriteLockImpl();
	void UnlockImpl();

private:
	pthread_rwlock_t m_rwl;
};

//-----------------------------------------------------------------

class CMyRWLock: private CRWLockImpl
{
public:

	//创建读/写锁
	CMyRWLock(){};

	//销毁读/写锁
	~CMyRWLock(){};

	//获取读锁
	//如果其它一个线程占有写锁,则当前线程必须等待写锁被释放,才能对保护资源进行访问
	void ReadLock();

	//尝试获取一个读锁
	//如果获取成功,则立即返回true,否则当另一个线程占有写锁,则返回false
	bool TryReadLock();

	//获取写锁
	//如果一个或更多线程占有读锁,则必须等待所有锁被释放
	//如果相同的一个线程已经占有一个读锁或写锁,则返回结果不确定
	void WriteLock();

	//尝试获取一个写锁
	//如果获取成功,则立即返回true,否则当一个或更多其它线程占有读锁,返回false
	//如果相同的一个线程已经占有一个读锁或写锁,则返回结果不确定
	bool TryWriteLock();

	//释放一个读锁或写锁
	void Unlock();

private:
	CMyRWLock(const CMyRWLock&);
	CMyRWLock& operator = (const CMyRWLock&);
};

inline void CMyRWLock::ReadLock()
{
	ReadLockImpl();
}

inline bool CMyRWLock::TryReadLock()
{
	return TryReadLockImpl();
}

inline void CMyRWLock::WriteLock()
{
	WriteLockImpl();
}

inline bool CMyRWLock::TryWriteLock()
{
	return TryWriteLockImpl();
}

inline void CMyRWLock::Unlock()
{
	UnlockImpl();
}

#endif
RWLockImpl.cpp

#include "RWLockImpl.h"

CRWLockImpl::CRWLockImpl()
{
	if (pthread_rwlock_init(&m_rwl, NULL))
		cout<<"cannot create reader/writer lock"<

    下边是测试代码

// pthread_rwlock.cpp : 定义控制台应用程序的入口点。
//

#include "RWLockImpl.h"

//创建一个读写锁对象
CMyRWLock g_myRWLock;
volatile int g_counter = 0;

//线程函数
void * StartThread(void *pParam)
{
	int lastCount = 0;
	for (int i = 0; i < 10000; ++i)
	{
		g_myRWLock.ReadLock();
		lastCount = g_counter;
		//在读锁域,两个线程不断循环交替访问全局变量g_counter
		for (int k = 0; k < 100; ++k)
		{
			if (g_counter != lastCount) 
				cout<<"the value of g_counter has been updated."<    编译,运行 
  


    运行结果与在Win32下用C++实现多线程读写锁的相同。

    欢迎转载,麻烦带上链接:http://blog.csdn.net/chexlong/article/details/7163233,谢谢合作!


你可能感兴趣的:(C/C++,Linux,并行编程)