Reputation: 171
I created a secondary thread using _beginthreadex
. When the process wants to stop. it has to terminate both threads. The issue is the secondary thread is waiting on some handle (using WaitForSingleObject
) and the main thread wants to terminate secondary one.
How can main thread notify the second thread to stop with WaitForSingleObject
and then terminate?
Upvotes: 5
Views: 2519
Reputation: 43311
Add new event which is used to stop the thread:
HANDLE hStopEvent;
hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
To stop another thread:
SetEvent(hStopEvent); // ask thread to stop
WaitForSingleObject(hThread, INFINITE); // wait when thread stops
In the thread code, replace WaitForSingleObject
with WaitForMultipleObjects
. Wait for exitsting event + hStopEvent
. When hStopEvent
is signaled, exit the thread function.
HANDLE hEvents[2];
hEvents[0] = <your existing event>;
hEvents[1] = hStopEvent;
for(;;) // event handling loop
{
DWORD dw = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
if ( dw == WAIT_OBJECT_0 )
{
// your current event handling code goes here
// ...
}
else if ( dw == WAIT_OBJECT_0 + 1 )
{
// stop event is set, exit the loop and thread function
break;
}
}
Upvotes: 16