您的位置:首页 > 其它

Readers/Writers lock

2015-07-26 19:37 274 查看

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: