In one of my projects, I created multiple auto reset events and two threads, the threads use WaitForMultipleObjects to wait on some events before continuing run, like:
HANDLE hTerminateEvent = CreateEvent(...); // auto reset
HANDLE hStateChangedEvent = CreateEvent(...); // auto reset
void thread1Func()
{
HANDLE handles[2] = { hTerminateEvent, hStateChangedEvent };
WaitForMultipleObjects(2, handles, FALSE/*bWaitAll*/, INFINITE);
...
}
void thread2Func()
{
HANDLE handles[2] = { hTerminateEvent, hStateChangedEvent };
WaitForMultipleObjects(2, handles, FALSE/*bWaitAll*/, INFINITE);
...
}
I previously thought that once hTerminateEvent is singled, both threads will be waken up, but seems that is not true for auto reset events, which one gets waken up is random, and after one wakes up, it reset the hTerminateEvent to un-signaled.
My question is how to resolve this: by using manual reset event? or does there exist any design to solve this problem? thanks!
If you want both threads to react to
hTerminateEventthen it must be set to manual reset. Presumably you are using it as a signal to tell multiple threads to terminate themselves, so it does not make sense to set it as auto reset anyway. Same withhStateChangedEvent.If you read the
CreateEvent()documentation, it says:So when using an auto-reset event, you cannot wake up multiple threads that are waiting on it at the same time.