aac
asked on
Killing a Thread outside the thread function
I want to kill a thread, AfxBeginThread(...). It is given that I can do so within the thread. I want to kill on pressing a command button.
Jalaja
Jalaja
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If your child thread is spending a lot of time waiting (with WaitForSingleObject() or simular), you could create a global manually event.
Modify you thread function to take the event into account:
----
extern HANDLE g_hAbortThreadSignal;
void MySmartThreadFunc(LPVOID lpvParam)
{
[....]
HANDLE hWaitHandles[] = { hSomeHandle, g_hAbortThreadSignal };
while(1)
{
DWORD dwResult = WaitForMultipleObjects(2, hWaitHandles, FALSE, INFINITE);
if(dwResult == (WAIT_OBJECT_0+1))
{
// Our abort signal set, exit thread function
return 0;
}
//
// Normal processing goes here!
//
}
return 0;
}
----
// To create the manual reset event insert this in CWinApp::InitInstance() or simular:
HANDLE g_hAbortThreadSignal;
g_hAbortThreadSignal = CreateEvent(NULL, TRUE, FALSE, NULL);
// Remember to destroy the event when exiting the app:
CloseHandle(g_hAbortThread Signal);
---
// To make the child thread exit, just signal the event from somewhere using the SetEvent() function:
SetEvent(g_hAbortThreadSig nal);
// (Remember to reset it again if you start the child thread again!)
Modify you thread function to take the event into account:
----
extern HANDLE g_hAbortThreadSignal;
void MySmartThreadFunc(LPVOID lpvParam)
{
[....]
HANDLE hWaitHandles[] = { hSomeHandle, g_hAbortThreadSignal };
while(1)
{
DWORD dwResult = WaitForMultipleObjects(2, hWaitHandles, FALSE, INFINITE);
if(dwResult == (WAIT_OBJECT_0+1))
{
// Our abort signal set, exit thread function
return 0;
}
//
// Normal processing goes here!
//
}
return 0;
}
----
// To create the manual reset event insert this in CWinApp::InitInstance() or simular:
HANDLE g_hAbortThreadSignal;
g_hAbortThreadSignal = CreateEvent(NULL, TRUE, FALSE, NULL);
// Remember to destroy the event when exiting the app:
CloseHandle(g_hAbortThread
---
// To make the child thread exit, just signal the event from somewhere using the SetEvent() function:
SetEvent(g_hAbortThreadSig
// (Remember to reset it again if you start the child thread again!)
Mistake, mistake.... The thread function should not return anything. Replace 'return 0' with just 'return'.
Often a better solution is to stash an abort flag somewhere, perhaps in your CWinApp object. The thread should have code to check this flag every once in a while and the command button can set the flag.