Harry Muscle
Harry Muscle

Reputation: 2377

WaitForSingleObject Returns Right Away When Called On Sleeping Thread

I have a thread that sleeps for long periods of time and when it comes time to shut it down I set an atomic variable that both the main program and the thread have access to and call WaitForSingleObject from the main program to wait until the thread exits. However, WaitForSingleObject returns right away with a WAIT_OBJECT_0 response telling me the thread has exited which can't be true cause it's sleeping (it sleeps for a minute at a time via the Sleep function and there's no way my call to WaitForSingleObject is always right before it wakes up and checks the shared variable).

My code to stop the thread is pretty straightforward:

gStopThread = true;
WaitForSingleObject(hThread, WAIT_INFINITE);
CloseHandle(hThread);

and in the thread I have:

while (!gStopThread)
{
   Sleep(60000);
   ...
}

Is this normal behavior from WaitForSingleObject? Does calling WaitForSingleObject possibly wake the thread up after which point it checks the shared variable and exits? But if that were the case the code after the Sleep function would get executed but it's not. Or does calling WaitForSingleObject on a sleeping thread simply shut the thread down (ie: it dies in its sleep)? Or is there another way to wait for a thread that is sleeping to wake up and gracefully exit?

Upvotes: 0

Views: 117

Answers (0)

Related Questions