分配一个SRWLOCK 结构并初始化
SRWLOCK srwLock;
VOID InitializeSRWLock(&srwLock);
写入者线程独占锁
获得独占访问权:
VOID AcquireSRWLockExclusive(&srwLock);
解除对资源的锁定:
VOID ReleaseSRWLockExclusive(&srwLock);
读取者共享
获取访问权限(非独占)
VOID AcquireSRWLockShared(&srwLock);
解除锁定
VOID ReleaseSRWLockShared(&srwLock);
-如果在锁被占用的时候,调用AcquireSRWLock*的时候会阻塞(调用线程
)。
-不能递归地获得SRWLOCK。
*具体代码和关键段类似。
SRWLOCK srwLock;
int dwData = 0;
unsigned __stdcall ThreadFuncRead(void* pIndex)
{
unsigned temp = (unsigned)pIndex;
int a = 0;
while(1)
{
a++;
AcquireSRWLockShared(&srwLock);
printf("[%d]thread %d read:%d\n",a,temp,dwData);
Sleep(1000);
ReleaseSRWLockShared(&srwLock);
}
return 1;
}
unsigned __stdcall ThreadFuncWrite(void*)
{
while (1)
{
AcquireSRWLockExclusive(&srwLock);
dwData++;
printf("Write %d\n",dwData);
Sleep(800);
ReleaseSRWLockExclusive(&srwLock);
}
return 1;
}
BOOL OnActive()
{
InitializeSRWLock(&srwLock);
int i=0;
HANDLE hThreadRead[3];
HANDLE hThreadWrite;
unsigned uiThreadReadID[3];
unsigned uiThreadWriteID;
hThreadWrite = (HANDLE)_beginthreadex(NULL,0,ThreadFuncWrite,0,CREATE_SUSPENDED,&uiThreadWriteID);
for (i=0;i<3;i++)
{
hThreadRead[i] = (HANDLE)_beginthreadex(NULL,0,ThreadFuncRead,(void*)i,CREATE_SUSPENDED,&(uiThreadReadID[i]));
}
ResumeThread(hThreadWrite);
ResumeThread(hThreadRead[0]);
ResumeThread(hThreadRead[1]);
ResumeThread(hThreadRead[2]);
Sleep(5000);
CloseHandle(hThreadWrite);
CloseHandle(hThreadRead[0]);
CloseHandle(hThreadRead[1]);
CloseHandle(hThreadRead[2]);
return TRUE;
}
网友评论