Readers/Writers lock
2015-07-26 19:37
274 查看
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/panic.gif)
Readers/Writers lock数据结构:
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/panic.gif)
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);
}
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/panic.gif)
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;
}
相关文章推荐
- 2015.7.26阅读笔记
- 有意思的一段代码
- HDU OJ Digital Roots 题目1013
- Web标准
- 关于控件内容绑定到类
- 云计算和大数据时代网络技术揭秘(十七)VOQ机制
- 火车进站 华为oj
- leetcode[80]:Remove Duplicates from Sorted Array II
- android初识二(电话拨号器&短信发送器)
- PAT (Advanced Level) 1050. String Subtraction (20) 字符串去除,哈希
- ftp工具root登入linux设置
- 关于DOCTYPE
- JAVA基础知识(2)--关键字static的使用
- F - Count the Colors - zoj 1610(区间覆盖)
- HTML+CSS学习笔记(一)——网页布局
- Overlapped I/O with APCs
- 数据结构——HDU1312:Red and Black(DFS)
- 开源那点事
- Ubuntu安装深度音乐&&深度影音
- 判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解