sazr
sazr

Reputation: 25928

WaitForSingleObject doesn't timeout

The following simple code doesn't operate as I expected. It creates a thread (suspended), starts it, waits for it to run for 1 millisecond and loops waiting until the thread dies or fails.

I expected the output to be something along the lines of:

Start
Callback running
Callback running
Callback running
WaitForSingleObject looping
Callback running
Callback running
WaitForSingleObject looping
Callback running
Callback running
WaitForSingleObject looping
Callback running
Callback running
... repeating for 10000 times
End
Thread end

But the output is:

Start
Callback running
Callback running
Callback running
Callback running
Callback running
... repeating for 10000 times
Callback running
End
WaitForSingleObject looping
Thread end

I thought that the wait in WaitForSingleObject would timeout at some point and interrupt the thread at some point? But the thread seems to be blocking and not asynchronous?

DWORD WINAPI callback(LPVOID param)
{
    printf("Start\n");

    for (int i=10000; i>0; i--)
        printf("Callback running\n");

    printf("End\n");
    return 1;
}

int main()
{
    HANDLE hThread = CreateThread(NULL, 0, callback, 0, CREATE_SUSPENDED, 0);

    if (!hThread) {
        printf("Failed to create thread\n");
        return 0;
    }

    ResumeThread(hThread);
    while (WaitForSingleObject(hThread, 1) == WAIT_TIMEOUT) {
        printf("WaitForSingleObject looping\n");
    }

    CloseHandle(hThread);
    printf("Thread end\n");

    system("PAUSE");
    return 0;
}

Upvotes: 1

Views: 2496

Answers (1)

MooseBoys
MooseBoys

Reputation: 6783

The dwMilliseconds parameter in WaitForSingleObject cannot be relied upon for accurate timing. The only contract is that after that much time has elapsed, the thread will eventually wake up and return the TIMEOUT value. The thread may not wake up until its next scheduled quanta, which can be as high as 60 milliseconds (or even higher on Windows Server). This is more than enough time for the second thread to complete. Try increasing the iteration count such that the worker thread takes at least one second to run - that should be plenty of time for the primary thread to be scheduled and run at least one more iteration of the TIMEOUT loop.

Upvotes: 2

Related Questions