WaitForMultipleObjectsEx

WaitForMultipleObjectsEx waits until one or all of the specified objects are in the signaled state, or the time-out interval elapses. It can also return while the thread is in an APC (asynchronous procedure call) queued state.

Syntax
C
DWORD WaitForMultipleObjectsEx(
    DWORD        nCount,
    const HANDLE *lpHandles,
    BOOL         bWaitAll,
    DWORD        dwMilliseconds,
    BOOL         bAlertable
);
Parameters
Return Value

If the function succeeds, the return value indicates the event that caused the function to return:

Remarks

The function can be used with any Windows synchronization object that can be waited on, such as events, mutexes, semaphores, timers, and thread handles.

When bAlertable is TRUE, the thread can execute APCs while waiting. This is useful for I/O completion ports.

Example
#include <windows.h>
#include <stdio.h>

int main(void)
{
    HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, L"MyEvent");
    if (!hEvent) return 1;

    // Simulate signaling after 2 seconds
    CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)[](LPVOID p)->{
        Sleep(2000);
        SetEvent((HANDLE)p);
        return 0;
    }, hEvent, 0, NULL);

    DWORD result = WaitForMultipleObjectsEx(1, &hEvent, FALSE, INFINITE, FALSE);
    if (result == WAIT_OBJECT_0) {
        printf("Event signaled!\\n");
    }

    CloseHandle(hEvent);
    return 0;
}

Comments

Alice
2024-08-12 14:22
Great explanation! The example helped me understand the alertable flag.
Bob
2024-08-13 09:07
Remember to close handles to avoid leaks. Thanks for the tip.