Skip to content
systemcoding.dev
Systems Programming

Wait on Objects with WaitForSingleObject and WaitForMultipleObjects

Use WaitForSingleObject and WaitForMultipleObjects to block on events, threads, processes and mutexes, read the return codes and avoid the 64 handle limit.

8 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, GNU and Linux logos.

Almost everything that takes time in a Win32 program can be waited for with the same two functions. A process that must finish, a thread that must exit, an event another thread will set, a mutex someone else holds, a timer that will fire: each is a kernel object with a state called signaled or non-signaled, and WaitForSingleObject and WaitForMultipleObjects block the calling thread until the state is signaled or a timeout expires. The blocked thread uses no processor. This uniformity is why Win32 programs can be structured as one wait on several things at once, and why most synchronization bugs come down to misreading what a wait returned or what it did to the object it waited on. This post covers the return codes, the side effects of a successful wait, the 64 handle limit and how to get around it, and a few cases where the wait is not what you want.

The examples use the Windows 11 SDK (10.0.26100) with MSVC 19.4 on x64. Both functions are documented on Microsoft Learn with a table of what "signaled" means for each object type.

What signaled means

The meaning depends on the type of object:

ObjectBecomes signaled whenA successful wait does
ProcessThe process exitsNothing; stays signaled
ThreadThe thread endsNothing; stays signaled
Manual-reset eventSetEvent is calledNothing; stays signaled until ResetEvent
Auto-reset eventSetEvent is calledResets it to non-signaled, releasing one waiter
MutexNo thread owns itThe waiter becomes the owner
SemaphoreIts count is above zeroDecrements the count by one
Waitable timerIt reaches its due timeManual-reset timers stay signaled; synchronization timers reset
Change notificationThe watched directory changesNothing; call FindNextChangeNotification to re-arm

The third column is the one to remember. A wait on some objects changes them. Waiting on an auto-reset event consumes the signal, so exactly one waiter proceeds. Waiting on a mutex makes you the owner, and you must release it with ReleaseMutex. Waiting on a semaphore takes a unit. These are the properties that make the objects useful for coordination, and ignoring them is the source of deadlocks.

One object

single.cc
#include <windows.h>
#include <process.h>
#include <stdio.h>

static HANDLE done;

static unsigned __stdcall worker(void *arg)
{
    (void)arg;
    Sleep(200);
    SetEvent(done);
    return 0;
}

int wmain(void)
{
    done = CreateEventW(NULL, TRUE, FALSE, NULL);     /* manual reset, off */
    HANDLE th = (HANDLE)_beginthreadex(NULL, 0, worker, NULL, 0, NULL);
    if (!done || !th)
        return 1;

    DWORD r = WaitForSingleObject(done, 50);
    if (r == WAIT_TIMEOUT)
        wprintf(L"after 50 ms: not done yet\n");

    r = WaitForSingleObject(done, 2000);
    if (r == WAIT_OBJECT_0)
        wprintf(L"done\n");

    WaitForSingleObject(th, INFINITE);
    CloseHandle(th);
    CloseHandle(done);
    return 0;
}
Shell
cl /nologo /W4 /DUNICODE /D_UNICODE single.c
single.exe
Text
single.c
after 50 ms: not done yet
done

The first wait gives up after 50 milliseconds, because the thread sleeps for 200, and returns WAIT_TIMEOUT. The second waits up to two seconds and succeeds with WAIT_OBJECT_0. A timeout of 0 tests the state without blocking, which is a poll. INFINITE blocks forever, and should be a deliberate choice, since a lost signal then hangs the program with nothing to show for it.

The complete list of return values:

ValueMeaning
WAIT_OBJECT_0The object is signaled, and the wait succeeded
WAIT_TIMEOUTThe time ran out
WAIT_FAILEDAn error, such as an invalid handle; call GetLastError
WAIT_ABANDONED_0A mutex whose owner thread ended without releasing it, now owned by you
WAIT_IO_COMPLETIONAn alertable wait ended because an I/O completion routine ran

WAIT_FAILED has the value 0xFFFFFFFF. Code that tests only if (WaitForSingleObject(h, t)) conflates success, which is zero, with everything else, so always compare with the named constants.

WAIT_ABANDONED deserves a note. If a thread ends while holding a mutex, the mutex is released and the next waiter gets WAIT_ABANDONED_0 as the success code. It means the protected data may be in an inconsistent state, because the previous owner never finished what it was doing. You own the mutex either way, and you decide whether to repair the data or give up.

Several objects

WaitForMultipleObjects takes an array of handles, and a flag that decides the condition:

c
DWORD WaitForMultipleObjects(
    DWORD nCount,            /* 1 to MAXIMUM_WAIT_OBJECTS (64) */
    const HANDLE *handles,
    BOOL  waitAll,           /* TRUE: all must be signaled; FALSE: any one */
    DWORD milliseconds);

With waitAll set to TRUE, the call returns when every object is signaled, and it acquires them atomically: either it gets all of them at once or none. That is what makes it safe for locking several mutexes without a deadlock from ordering. With FALSE, it returns as soon as any one is signaled, and the return value tells you which: WAIT_OBJECT_0 + index, where index is the position in the array. If several are signaled at once, it reports the one with the lowest index, so the order of the array is a priority order.

any.cc
#include <windows.h>
#include <process.h>
#include <stdio.h>

static HANDLE ev[2];

static unsigned __stdcall signal_later(void *arg)
{
    unsigned which = (unsigned)(uintptr_t)arg;
    Sleep(100 + 100 * which);
    SetEvent(ev[which]);
    return 0;
}

int wmain(void)
{
    HANDLE th[2];
    for (unsigned i = 0; i < 2; i++) {
        ev[i] = CreateEventW(NULL, FALSE, FALSE, NULL);   /* auto reset */
        th[i] = (HANDLE)_beginthreadex(NULL, 0, signal_later,
                                       (void *)(uintptr_t)i, 0, NULL);
    }

    for (int received = 0; received < 2; received++) {
        DWORD r = WaitForMultipleObjects(2, ev, FALSE, 5000);
        if (r >= WAIT_OBJECT_0 && r < WAIT_OBJECT_0 + 2)
            wprintf(L"event %lu signaled\n", r - WAIT_OBJECT_0);
        else if (r == WAIT_TIMEOUT)
            wprintf(L"timed out\n");
        else
            wprintf(L"wait failed: %lu\n", GetLastError());
    }

    WaitForMultipleObjects(2, th, TRUE, INFINITE);
    for (int i = 0; i < 2; i++) {
        CloseHandle(th[i]);
        CloseHandle(ev[i]);
    }
    return 0;
}
Text
event 0 signaled
event 1 signaled

The events are auto-reset, so each SetEvent is consumed by exactly one successful wait. If the events were manual-reset, the first would stay signaled and the second loop iteration would report event 0 again and never see event 1, an instructive bug. When a manual-reset event is used with a wait-any loop, call ResetEvent on the one you have handled.

The range check r >= WAIT_OBJECT_0 && r < WAIT_OBJECT_0 + 2 is how the documentation recommends distinguishing the index results from the special codes. Since WAIT_OBJECT_0 is 0, the subtraction yields the index directly.

The limit of 64

MAXIMUM_WAIT_OBJECTS is 64. Passing more fails with ERROR_INVALID_PARAMETER. Three ways around it:

Wait on a group, then a second level. Spawn helper threads that each wait on up to 63 handles and set a single event when any fires. The main thread waits on the helpers' events.

Reduce the number of objects. Many tasks can be signaled through one event plus a shared queue protected by a lock. The waiter wakes, drains the queue, and sleeps again. This is usually simpler and faster than 100 events.

Use a different mechanism. An I/O completion port handles any number of operations with a few threads, and the thread pool's wait objects register callbacks without a dedicated thread per wait.

Waiting in a program with a window

A thread that owns windows must keep pumping messages, or its windows freeze. A plain WaitForSingleObject on that thread blocks the pump. The tool for this case is MsgWaitForMultipleObjects, which waits for handles or for input messages. It returns WAIT_OBJECT_0 + count when a message is waiting, at which point you process it with PeekMessage and DispatchMessage and wait again. The simpler design is to keep the user interface thread free of waits, do waiting on a worker thread, and post a message back with PostMessageW when the work is done.

Alertable waits and APCs

WaitForSingleObjectEx and WaitForMultipleObjectsEx take an extra bAlertable argument. When it is TRUE, the thread can also be woken to run an asynchronous procedure call, a function queued to that thread with QueueUserAPC or an I/O completion routine given to ReadFileEx. The wait then returns WAIT_IO_COMPLETION after the routine has run. This is a niche mechanism that suits some I/O patterns, and an unexpected WAIT_IO_COMPLETION is the clue that the thread was alertable when something queued work to it.

Patterns that work

A shutdown event plus work events. Every worker loop waits on its work object and a manual-reset shutdown event. When the program ends, setting the shutdown event wakes every worker at once, and each exits cleanly:

c
HANDLE waits[2] = { work_event, shutdown_event };
for (;;) {
    DWORD r = WaitForMultipleObjects(2, waits, FALSE, INFINITE);
    if (r == WAIT_OBJECT_0 + 1)
        break;                      /* shutdown */
    if (r == WAIT_OBJECT_0)
        process_work();
    else
        break;                      /* failure */
}

The order puts work first; if both are signaled, the call reports work, which means a shutdown waits until the pending work is processed. Swap the order to make shutdown take priority.

A timeout as a heartbeat. Waiting with a timeout of a few seconds and using WAIT_TIMEOUT as the signal to do periodic housekeeping avoids a separate timer thread.

Waiting for a child with a limit. WaitForSingleObject(pi.hProcess, 30000) followed by TerminateProcess on timeout is the standard way to bound a child's runtime.

Mistakes that cause hangs and races

Waiting on a closed or wrong handle. A closed handle returns WAIT_FAILED with ERROR_INVALID_HANDLE, but a handle value reused by another object waits on the wrong thing. Set handles to NULL after closing and check for them.

**Assuming INFINITE is safe.** If the signal never comes, because the thread that should set the event crashed, the waiter hangs forever. Prefer a long timeout with logging.

Consuming a signal twice. With an auto-reset event or a semaphore, a successful wait consumes the signal. Two threads waiting on the same auto-reset event wake one at a time, not both.

**Forgetting ReleaseMutex after a wait.** A mutex wait that succeeds makes you the owner, and every path out of the protected code must release it. Release it the same number of times as you acquired it, since a mutex can be recursively owned.

**Waiting inside DllMain.** The loader lock is held there. Waiting for another thread that also needs it deadlocks.

Polling. A loop that tests GetExitCodeThread or a flag and calls Sleep(10) wastes time and adds latency. Wait on the handle.

**Using bWaitAll with objects that can become signaled for different reasons.** The call returns only when all are signaled at the same instant. An auto-reset event consumed by another waiter in the meantime may mean that moment never comes.

Reading the wrong index. Subtract WAIT_OBJECT_0 first, and handle WAIT_ABANDONED_0 + i separately from WAIT_OBJECT_0 + i when mutexes are in the array.

When waiting is the wrong tool

For waiting on many sockets or I/O operations, completion ports scale better. For waiting on a condition inside one process, the lighter CONDITION_VARIABLE with an SRWLOCK avoids a kernel transition when there is no contention. For waiting on an address to change, WaitOnAddress is an efficient primitive on newer Windows versions. Use the kernel wait functions when the object is a kernel object, which is when you need cross-process behavior, a process or thread handle, or a single call that combines several different kinds.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.