Behavior of WaitForMultipleObjects when multiple handles signal at the same time

后端 未结 4 951
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 09:24

Given: I fill up an array of handles with auto reset events and pass it off to WaitForMultipleObjects with bWaitAll = FALSE.

From MSDN: “When bWaitAll is FALSE, th

相关标签:
4条回答
  • 2021-01-13 09:39

    One other option you might have is to use RegisterWaitForSingleObject. The idea is that you flag the signaled state of event in a secondary array from the callback function and then signal a master event which is used to wake up your primary thread (which calls WaitForSingleObject on the master event).

    Obviously you'd have to take care to ensure that the secondary array was protected from access by the main thread but it would work.

    0 讨论(0)
  • 2021-01-13 09:42

    Only the auto-reset event that ended the wait (whose index is returned) will be reset. If the wait times out no events will be reset.

    cf https://blogs.msdn.microsoft.com/oldnewthing/20150409-00/?p=44273

    0 讨论(0)
  • 2021-01-13 09:48

    So, now if multiple objects signal I’ll get the index of the first one. Do I have to loop though my array to see if any others have signaled?

    Why not just go back round into the Wait()? if multiple objects signalled, they will still be signalled when you come back round. Of course, if you have a very rapidly firing first object in the wait object array, it will starve the others; what you do is order your objects in the wait object array by frequency of firing, with the least frequent being first.

    BTW, where you're using an endless for(), you could use a goto. If you really are not leaving a loop, an unconditional goto most properly expresses your intent.

    0 讨论(0)
  • 2021-01-13 09:56

    Yes. One alternative would be that you could do WaitForSingleObject(handle, 0) on each handle which will return immediately and indicate if they are signaled or not.

    EDIT: Here's sample pseudocode for what I mean:

    ret = WaitForMultipleObjects()
    if (ret >= WAIT_OBJECT_0 && ret < WAIT_OBJECT_0 + (count))
    {
        firstSignaled = ret - WAIT_OBJECT_0;
    
        // handles[firstSignaled] guaranteed signalled!!
    
        for (i = firstSignaled + 1; i < count; i++)
        {
            if (WaitForSingleObject(handles[i], 0) == WAIT_OBJECT_0)
            {
               // handles[i] Signaled!
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题