Tuesday 15 May 2012

WaitForMultipleObjects and priority of the events

The order of event handlers in the handler array passed to WaitForMultipleObjects function must be carefully chosen if we want to differentiate priorities of events.

Let us assume that we have two events, Event1 and Event2, and that we want Event2 to have a higher priority so if both events are set, WaitForMultipleObjects returns the index of the Event2. We can make this by defining the order of the event handlers in the array passed to WaitForMultipleObjects.

In the example below, Event2 controls when the program execution jumps out of the loop. If Event1 is set quickly enough between ResetEvent() and WaitForMultipleObjects, it is Event1 that will always cause WaitForMultipleObjects to return, no matter what is the state of Event2. Execution will get out of the loop only if Event2 is set and Event1 is not set before WaitForMultipleObjects (which might never happen):

If we want to make sure that WaitForMultipleObjects first checks whether Event2 is set so it breaks out of the loop as soon as this event is set, we need to place Event2 before Event1 in the array:

This time, even if both events are set, WAIT_OBJECT_0 case is executed and program flow leaves the loop.

This is the consequence of the following feature of WaitForMultipleObjects:

If more than one object became signaled during the call, WAIT_OBJECT_0 is the array index of the signaled object with the smallest index value of all the signaled objects.

No comments: