Linux学习之"互斥量实现多读单写锁"

测试(其余代码相同):

View Code
#include <iostream>
#include <unistd.h>
#include "CLThread.h"
#include "CLExecutiveFunctionProvider.h"
#include "CLMutex.h"
#include "CLCriticalSection.h"

using namespace std;

int global = 0;

class CLMyFunction : public CLExecutiveFunctionProvider
{
public:
CLMyFunction()
{
}

virtual ~CLMyFunction()
{
}

virtual CLStatus RunExecutiveFunction(void *pContext)
{
CLMutex *pReadMutex = (CLMutex *)pContext;
{
CLCriticalSection cs(pReadMutex);
cout << "this is " << pthread_self() << endl;
cout << global << endl;
}
return CLStatus(0, 0);
}
};

int main()
{
CLMutex *pReadMutex1 = new CLMutex();
CLMutex *pReadMutex2 = new CLMutex();
CLMutex *pWriteMutex = new CLMutex();

CLExecutiveFunctionProvider *myfunction1 = new CLMyFunction();
CLExecutive *pThread1 = new CLThread(myfunction1);
pThread1->Run((void *)pReadMutex1);

CLExecutiveFunctionProvider *myfunction2 = new CLMyFunction();
CLExecutive *pThread2 = new CLThread(myfunction2);
pThread2->Run((void *)pReadMutex2);

{
CLCriticalSection cs1(pReadMutex1);
CLCriticalSection cs2(pReadMutex2);
CLCriticalSection cs3(pWriteMutex);

global++;
}

pThread1->WaitForDeath();
pThread2->WaitForDeath();

delete pThread2;
delete pThread1;
delete myfunction1;
delete myfunction2;

delete pReadMutex1;
delete pReadMutex2;
delete pWriteMutex;

return 0;
}

对写来说(从加写锁到释放写锁),就是要获得其它每个读锁(读互斥量)。
注意添加的那对大括号,保证了范围内锁的释放。

posted @ 2011-10-21 22:49  lq0729  阅读(511)  评论(0编辑  收藏  举报