标签:
Readers/Writers lock数据结构:
READWRIT的InitRWLock()
BOOL InitRWLock(RWLock *pLock)
{
pLock->nReaderCount = 0;
pLock->hDataLock = CreateSemaphore(NULL, 1, 1, NULL);
if (pLock->hDataLock == NULL)
return FALSE;
PLock->hMutex = CreateMutex(NULL, FALSE, NULL);
if (pLock->hMutex == NULL)
{
CloseHandle(pLock->hDataLock);
return FALSE;
}
return TRUE;
}
所面对的下一个问题是如何加上错误处理函数,产生一个名为MyWaitForSingleObject()的函数,如下:
BOOL MyWaitForSingleObject(HANDLE hObject)
{
int result;
result = WaitForSingleObject(hObject, MAXIMUM_TIMEOUT);
//Comment this out if you want this to be non-fatal
if (result != WAIT_OBJECT_0)
FatalError("MyWaitForSingleObject - "
"Wait failed,you probably forgot to call release!");
return (result == WAIT_OBJECT_0);
}
READWRIT的ReadOK()和WriteOK()
BOOL ReadOK(RWLock *pLock)
{
//This check is not perfect,because we
//do not know for sure if we are one of this readers
return (pLock->nReaderCount > 0);
}
BOOL WriteOK(RWLock *pLock)
{
DWORD result;
//The first reader may be waiting in the mutex
// but any more than that is an error
if (pLock->nReaderCount > 1)
return FALSE;
//This check is not perfect,because we do not know
//for sure if this thread was the one that hand the
//semaphore locked.
result = WaitForSingleObject(pLock->hDataLock, 0);
if (result == WAIT_TIMEOUT)
return TRUE;
// a count is kept,which was incremented in Wait
result = ReleaseSemaphore(pLock->hDataLock,1,NULL);
if (result == FALSE)
FatalError("WriteOK - ReleaseSemaphore failed");
return FALSE;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/wangfengfan1/article/details/47068043