Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of SignalObjectAndWait regards there is SetEvent and WaitForSingleObject?

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?

like image 938
ZijingWu Avatar asked Aug 17 '13 13:08

ZijingWu


People also ask

What does SetEvent do?

Sets the specified event object to the signaled state.

How do you signal on Waitforsingleobject?

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.


2 Answers

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 as SetEvent followed by WaitForSingleObject.

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".

like image 175
Roman R. Avatar answered Oct 23 '22 14:10

Roman R.


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.

like image 42
Mats Petersson Avatar answered Oct 23 '22 15:10

Mats Petersson