WaitForSingleObject, How to stop a thread?
I thought that WaitForSingleObject would return immediately for a thread which is stoped, but in the code below the WaitForSingleObject seems to wait infinitely. Why ?
Code:
volatile bool stop;
DWORD WINAPI SampleThread(LPVOID iValue)
{
while(!stop) {
Sleep(500);
}
return 0;
}
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
stop=false;
HANDLE hThread;
DWORD dwGenericThread;
hThread = CreateThread(NULL,0,SampleThread,NULL,0,&dwGenericThread);
if(hThread == NULL)
{
DWORD dwError = GetLastError();
return;
}
stop=true;
WaitForSingleObject(hThread,INFINITE);
return;
}
Re: WaitForSingleObject, How to stop a thread?
What is the waitforsingleobject doing ??
Code:
// thread is stopping here. .
stop=true;
// what are you waiting for ??
WaitForSingleObject(hThread,INFINITE);
Re: WaitForSingleObject, How to stop a thread?
Skizmo's got your number here.
I can see you're testing theory of design here, the stop flag adjustment might seem like a good test, but Skizmo's identified a flaw.
It's entirely possible that the thread object is GONE before you wait.
Either signal the stop from some other thread, or...start your thread suspended.
Or, consider using an event.
The whole design goal is to wait on thread completion, but there are other concepts in threads you might wait on that will imply an event anyway.
It's better, most of the time, to create a thread that waits on an event so that you can fill a queue with 'jobs' for it to run. This means you'd have an event anyway.
You could construct this wait on an autoreset event. If you had, and the exit from the thread process had signaled that event, you wouldn't have this bug.
If you prefer to wait on the thread, you have to be certain it's not possible, even if unlikely, that the thread could have completed before you entered the wait.
Re: WaitForSingleObject, How to stop a thread?
Quote:
Originally Posted by Divad
I thought that WaitForSingleObject would return immediately for a thread which is stoped, but in the code below the WaitForSingleObject seems to wait infinitely. Why ?
Well, man, your code indeed returns immediately. So your thought was absolutely correct. :)
Re: WaitForSingleObject, How to stop a thread?
Your code is correct. even the thread completed before you wait, it will still returns immediately.
Re: WaitForSingleObject, How to stop a thread?
My example actually work. The problem was my debugger. When I stepwise went through my program, it halt infinately.