I'm not clear about this, can someone confirm this for me?
I have the following synchronization issue. I have the following objects:
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.
And here's the access conditions:
- A must be blocked while B or C are on.
- B must be blocked only while A is on.
- C must be blocked only while A is on.
So I thought to use 2 named mutexes for that:
- hMutex2 = used to satisfy condition 2 above.
- hMutex3 = used to satisfy condition 3 above.
- hStopEvent = a stop event (needs to stop the thread if the app is closing).
So for 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
}
For B:
DWORD dwRes = WaitForSingleObject(hMutex2, INFINITE);
if(dwRes == WAIT_OBJECT_0)
{
//Do reading here
...
//Release ownership
ReleaseMutex(hMutex2);
}
else
{
//Error
}
For C:
DWORD dwRes = WaitForSingleObject(hMutex3, INFINITE);
if(dwRes == WAIT_OBJECT_0)
{
//Do reading here
...
//Release ownership
ReleaseMutex(hMutex3);
}
else
{
//Error
}
Can someone confirm this:
- When calling WaitForMultipleObjects on both mutexes, do they both become signaled (or blocked)?
- Also do I needs to release both mutexes?
As a matter of fact, I can contradict it.
WaitForMultipleObjects
with thewaitAll
parameter set toFALSE
will return if any of the objects are signaled. Here's the documentation :) Set it toTRUE
and you'll have it waiting for all objects.Your solution doesn't scale well, though: add another reading thread, and you're stuck with a third mutex...
The Writer/Readers problem has been solved many times before, however; why not take a look into existing implementations? Will save you a lot of debug time, especially if you're not yet familiar with the windows synchronization API. (Teaser: posix threads have a readwritelock, boost has a
shared_mutex
.)