I just realized there is SignalObjectAndWait
API function for Windows platform. But there is already SetEvent
and WaitForSingleObject
. You can use them together to achieve the same goal as SignalObjectAndWait
.
Based on the MSDN, SignalObjectAndWait
is more efficient than separate calls to SetEvent
and WaitForSingleObject
. It also states:
A thread can use the
SignalObjectAndWait
function to ensure that a worker thread is in a wait state before signaling an object.
I don't fully understand this sentence, but it seems that efficiency is not the only reason why we need SignalObjectAndWait
. Can anybody provide a scenario where SetEvent
+ WaitForSingleObject
fails to provide the functionality that SignalObjectAndWait
offers?
Sets the specified event object to the signaled state.
Waits until the specified object is in the signaled state or the time-out interval elapses. To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use WaitForMultipleObjects.
My understanding is that this single function is more efficient in the way that it avoid the following scenario.
The
SignalObjectAndWait
function provides a more efficient way to signal one object and then wait on another compared to separate function calls such asSetEvent
followed byWaitForSingleObject
.
When you you SetEvent
and another [esp. higher priority] thread is waiting on this event, it might so happen that thread scheduler takes control away from the signaling thread. When the thread receives control back, the only thing that it does is the following WaitForSingleObject
call, thus wasting context switch for such a tiny thing.
Using SignalObjectAndWait
you hint the kernel by saying "hey, I will be waiting for another event anyway, so if it makes any difference for you don't excessively bounce with context switches back and forth".
The purpose, as MSDN explains is to ensure that the thread is in a Wait State BEFORE the event is signalled. If you call WaitForSingleObject, the thread is in a waitstate, but you can't call that BEFORE calling SetEvent, since that will cause SetEvent to happen only AFTER the wait has finished - which is pointless if nothing else is calling SetEvent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With