【发布时间】:2012-06-09 17:42:11
【问题描述】:
我不清楚,有人可以帮我确认一下吗?
我有以下同步问题。我有以下对象:
A. Process 1, thread 1: Read & write access to the resource.
B. Process 1, thread 2: Read access to the resource.
C. Process 2, thread 3: Read access to the resource.
这是访问条件:
- 必须在 B 或 C 开启时阻止 A。
- 只有在 A 开启时才能阻止 B。
- 只有在 A 开启时才能阻止 C。
所以我想为此使用 2 个命名互斥锁:
- hMutex2 = 用于满足上述条件 2。
- hMutex3 = 用于满足上述条件 3。
- hStopEvent = 一个停止事件(如果应用正在关闭,则需要停止线程)。
所以对于 A:
HANDLE hHandles[3] = {hMutex2, hMutex3, hStopEvent};
DWORD dwRes = WaitForMultipleObjects(3, hHandles, FALSE, INFINITE);
if(dwRes == WAIT_OBJECT_0 + 2)
{
//Quit now
return;
}
else if(dwRes == WAIT_OBJECT_0 + 0 ||
dwRes == WAIT_OBJECT_0 + 1)
{
//Do reading & writing here
...
//Release ownership
ReleaseMutex(hMutex2);
ReleaseMutex(hMutex3);
}
else
{
//Error
}
对于乙:
DWORD dwRes = WaitForSingleObject(hMutex2, INFINITE);
if(dwRes == WAIT_OBJECT_0)
{
//Do reading here
...
//Release ownership
ReleaseMutex(hMutex2);
}
else
{
//Error
}
对于 C:
DWORD dwRes = WaitForSingleObject(hMutex3, INFINITE);
if(dwRes == WAIT_OBJECT_0)
{
//Do reading here
...
//Release ownership
ReleaseMutex(hMutex3);
}
else
{
//Error
}
有人可以确认一下吗:
- 在两个互斥体上调用 WaitForMultipleObjects 时,它们是否都变为信号(或阻塞)?
- 我还需要释放两个互斥锁吗?
【问题讨论】:
-
你想要一个“读写器”锁。如果内存服务,它可以在没有 WaitForMultipleObjects 的情况下完成。 (您可能需要 WaitFSO)。我会看看我是否可以在今天晚些时候挖掘一个实现。在此之前 Bing 用于“读者作者锁定”
标签: c++ winapi synchronization mutex waitformultipleobjects