WaitForSingleObject

Synopsis

DWORD WaitForSingleObject(
    HANDLE hHandle,
    DWORD  dwMilliseconds
);

Parameters

NameDescription
hHandle Handle to the object. This can be a thread, mutex, semaphore, event, or any waitable handle.
dwMilliseconds Time-out interval, in milliseconds. Use INFINITE to wait forever.

Return value

If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following constants:

Remarks

This function waits until the specified object is in the signaled state or the time-out interval elapses. It can be used with any synchronization object that supports waiting.

When waiting on a mutex, WAIT_ABANDONED indicates that the owning thread terminated without releasing the mutex. In this case, the mutex is still owned by the calling thread.

Example

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

DWORD WINAPI ThreadProc(LPVOID lpParam) {
    Sleep(2000); // Simulate work
    printf("Thread finished.\n");
    return 0;
}

int main(void) {
    HANDLE hThread = CreateThread(
        NULL, 0, ThreadProc, NULL, 0, NULL);
    if (hThread == NULL) {
        printf("CreateThread failed (%lu)\n", GetLastError());
        return 1;
    }

    DWORD dwResult = WaitForSingleObject(hThread, 3000);
    if (dwResult == WAIT_OBJECT_0) {
        printf("Thread signaled within timeout.\n");
    } else if (dwResult == WAIT_TIMEOUT) {
        printf("Timeout waiting for thread.\n");
    } else {
        printf("Wait failed (%lu)\n", GetLastError());
    }

    CloseHandle(hThread);
    return 0;
}

See Also