我不清楚这一点,有人可以帮我确认一下吗?
我有以下同步问题。我有以下对象:
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.
这是访问条件:
- A 必须在 B 或 C 打开时被阻止。
- 只有在 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
}
对于 B:
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 时,它们是否都变为信号(或阻塞)?
- 我还需要释放两个互斥锁吗?