Synopsis
DWORD WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds
);
Parameters
| Name | Description |
|---|---|
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:
WAIT_OBJECT_0– The state of the specified object is signaled.WAIT_TIMEOUT– The time-out interval elapsed, and the object's state is nonsignaled.WAIT_ABANDONED– The specified object is a mutex that was not released by the thread that owned it before the owning thread terminated.WAIT_FAILED– The function has failed. CallGetLastErrorfor extended error information.
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;
}