Since comments are closed for me, I had to post my comments to previous posts as an answer. But actually I'm not answering.
1) There's a problem with @Alan 's solution.
The sample code he provided works well. But it is different from Windows Events functionality. When a Windows Event object is set, any number of subsequent calls to WaitForSingleObject
immediately returns, showing that the object is in signaled state. But with boost's mutex
/condition
solution, bar()
has to notify the condition for every foo()
calls that need it. This makes situation a lot harder for 'cross-platform'ing Windows Event functionality. notify_all()
also can't help.
Of course this is somehow solved in @deft_code's sample code by using a boolean variable. (Although it suffers itself from race condition problem. Consider if SetEvent(...)
is called dead after while(!evt->m_bool)
and before evt->m_cond.wait(lock)
from within a separate thread. A deadlock will occur. This can however be solved by using some race condition management techniques to make the two statements while()
and wait()
atomic.) But it has its own shortcoming:
2) There's also a problem with @deft_code 's code in making use of boost mutex
/condition
/bool
combination:
Event objects in Windows can be named which enables them to be used for inter-process synchronizations. For example, process A can create a named event and set it like this: SetEvent(hFileIsReady)
. Afterward, whatever number of processes waiting for this event to be set (thereby calling WaitForSingleObject(hFileIsReady)
) will immediately continue their normal execution until the event is again reset within process A by ResetEvent(hFileIsReady)
.
But the combination mutex
/condition
/bool
can't afford such a functionality. Of course, we can use boost named_condition
and named_mutex
. However, what about the boolean variable which we have to check before waiting?