码迷,mamicode.com
首页 > 其他好文 > 详细

Readers/Writers lock

时间:2015-07-26 20:59:47      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

技术分享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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Readers/Writers lock

标签:

原文地址:http://blog.csdn.net/wangfengfan1/article/details/47068043

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!