I have a DLL which contains a thread function whose pseudocode looks like:
volatile BOOL stopped = FALSE;
/* Enter critical section */
stopped = TRUE;
/* Leave critical section */
/* Checkpoint 1 */
/* Do cleanup */
/* Checkpoint 2 */
/* Do cleanup */
And in the code which uses this DLL, the cleanup function looks like:
/* 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?
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.
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.