Reputation: 2351
I have a DLL which contains a thread function whose pseudocode looks like:
volatile BOOL stopped = FALSE;
void StopEverything()
{
/* Enter critical section */
stopped = TRUE;
/* Leave critical section */
}
void workerThreadFunc()
{
Initialize();
/* Checkpoint 1 */
if(stopped)
{
/* Do cleanup */
return;
}
doLaboriousTask1();
/* Checkpoint 2 */
if(stopped)
{
/* Do cleanup */
return;
}
doLaboriousTask2();
Uninitialize();
}
And in the code which uses this DLL, the cleanup function looks like:
void cleanup()
{
StopEverything();
/* Wait for all threads to exit */
/* Do other cleanup */
}
My question is twofold:
workerThreadFunc()
from executing instead of doing checks like that at various checkpoints?workerThreadFunc()
is stuck inside doLaboriousTask2()
when the main application calls StopEverything()
. Is there a way to interrupt doLaboriousTask2()
and have it exit immediately?Thanks!
Upvotes: 3
Views: 3099
Reputation: 613612
Is there a better way to stop my workerThreadFunc() from executing instead of doing checks like that at various checkpoints?
Probably not. There's no fully reliable way to pre-emptively halt a thread in unmanaged code. Anything that purports to do that leads to TerminateThread
. And the documentation lists all sorts of dire consequences for using that function. For example:
- If the target thread owns a critical section, the critical section will not be released.
- If the target thread is allocating memory from the heap, the heap lock will not be released.
- If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
- If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.
You ask:
Is there a way to interrupt doLaboriousTask2() and have it exit immediately?
Well, you could call TerminateThread
but, for all the reasons described in the documentation, you almost certainly should not do that.
Upvotes: 3