Click to See Complete Forum and Search --> : Kill worker thread
dentist
July 6th, 1999, 10:46 AM
hi all,
can anyone tell me please, how to kill a worker thread correctly, when closing my app. i have started the thread in CMainFrm.
please help.... thx...
Dhwanit
July 6th, 1999, 01:52 PM
It is not recommended to "kill" a thread when the application quits. A better and recommended way would be to have a flag (global) in the application that will be switched "on" when the ExitInstance of the application class is entered. All worker threads must keep a watch on this and when this flag comes "on", must relinquish whatever they're doing and end themselves (AfxEndThread). Don't try this function from outside the thread. They must be used within the executing thread to terminate themselves.
Cheers!
DP
renga
July 6th, 1999, 04:30 PM
A better would be to use messages. You can create a message loop in your worker thread function.
You can assign WM_USER + 1 message that would terminate yor thread.
You would also assign WM_USER +2 as the message to do your work. In your message loop you can use GetMessage and check for WM_USER +1.When you want to terminate the thread when your main application ends, you can call PostThreadMessage API from your Application's OnDestroy function. You will pass WM_USER+1 in that API.
.
.
void OnDestroy()
{
PostThreadMessage(threadid,WM_USER+1,0,0)
}
void ThreadFunc()
{
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
if(msg.message== WM_USER+1)
AfxEndThread(0);
elseif(msg.message==WM_USER+2)
// do your work
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.