Search code examples
c++windowswaitforsingleobject

Two WaitForSingleObject in a if condition instead of WaitForMultipleObjects


Is it a valid way to put 2 WaitForSingleObject in a 'if' condtion. and I know it can be re-written using WaitForMuiltipleObject. But I wanted to know if I use below code would lead to any problems..?

CHandle     m_hEventUDP;
CHandle     m_hEventTCP;

if (WaitForSingleObject(m_hEventUDP, 1500) == WAIT_OBJECT_0 || WaitForSingleObject(m_hEventTCP, 1500) == WAIT_OBJECT_0)
{
    //An event is triggered(among 2)
    //I don't care which event is triggered among 2, either of one is Okay for me
}

else
{
    //No event is triggered
}

Solution

  • That will wait for the first one, and if that doesn't happen (and times out) only then will it wait for the second one. You can have one of three situations:

    • Both timeout. You take 3 seconds and get to the "no trigger" case.
    • One times out, one triggers. You take 1.5 seconds and get to the "trigger" case.
    • Both trigger, you get there as soon as the second one triggers.

    With WaitForMultipleObjects you will get this behaviour:

    • One triggers, you get there as soon as the first one triggers.
    • Both timeout, you take 1.5 seconds (or 3, if you indicate that) and get to the "no trigger" case.

    So in your current code you will have a 1.5 second latency added on in common cases, which the multiple objects wait avoids.