ACE读写锁(写优先)测试及用法

来源:互联网 发布:java分词器 编辑:程序博客网 时间:2024/05/16 12:52

在网络编程中多线程是一个必用一种技术,但是在初步学习多线程的时候很多人会遇到这样或那样的问题。多线程编程时,在有读线程和写线程并发的时候就需要读写锁了。ACE的读写锁机制完全可以解决这些问题。

ACE定义了四个宏,也就是:ACE_WRITE_GUARDACE_WRITE_GUARD_RETURNACE_READ_GUARDACE_READ_GUARD_RETURN。这四个宏的目的是为了实现高效的读写机制。其实就是定义两种对象:ACE_Read_GuardACE_Write_Guard。这两个类的意义在于在构造的时候,自动对应类型的锁,在析构的时候释放。

ACE的读写锁是写优先的,即:当有写线程想要写时,后面的读线程要处于阻塞状态,等待写线程退出时再开始加锁进行读操作。

下面是ACE读写锁的用法和测试,仅供参考。

#include <iostream>#include <time.h>#include <ace/Guard_T.h>using namespace std;#define MAX 100long counter = 0L;ACE_RW_Thread_Mutex m_cMutex;//写优先DWORD WINAPI ReadFun(LPVOID lpParamter){InterlockedIncrement(&counter);    ACE_READ_GUARD_RETURN(ACE_RW_Thread_Mutex, guard, m_cMutex, -1);cout<<"begin  read"<<endl;int* a = (int*)lpParamter;cout<<"read:"<<*a<<endl;cout<<"end  read"<<endl;InterlockedDecrement(&counter);return 0;}DWORD WINAPI WriteFun(LPVOID lpParamter){    ACE_WRITE_GUARD_RETURN(ACE_RW_Thread_Mutex, guard, m_cMutex, -1);cout<<"///////////////////////////////////////"<<endl;cout<<"the number of readers which is waiting to read: "<<counter<<endl;cout<<"begin write"<<endl;Sleep(4000);int* a = (int*)lpParamter;(*a)++;cout<<"write:"<<*a<<endl;cout<<"end write"<<endl;cout<<"///////////////////////////////////////"<<endl;return 0;}int main(int argc, char* argv[]){int a = 10;int* pa = &a;int i = 0;srand(time(0)); while(i != MAX){int tmp = rand()%10;if((tmp == 0) || tmp == 1 /*|| tmp ==2*/){HANDLE WHandle = CreateThread(NULL, 0, WriteFun, (void*)pa, 0, NULL);CloseHandle(WHandle);}else{HANDLE RHandle = CreateThread(NULL, 0, ReadFun, (void*)pa, 0, NULL);CloseHandle(RHandle);}i++;Sleep(1000);//阻塞一秒,否则运行太快,总是读或写}system("pause");return 0;}

当出现连续写的时候,可以看见在写的时候有读线程在等待,直到没有写线程等待时才开始读。由此看出该读写锁是写优先的。