We develop a finite element application with a facility for users to abort analysis while it is running. Because the analysis code is not structured to poll a stop flag regularly and needs to clean up which TerminateThread() does not do we wrote our own kill routine:

Code:
void KillThread(HANDLE hThread)
{
	CSingleLock cSLock(KillThreadCrit());
	_lock(_HEAP_LOCK);
	_lock(_TIME_LOCK);
	AfxLockGlobals(CRIT_LOCKSHARED);

	// kill thread
	if(::SuspendThread(hThread) != 0xffffffff)
	{
		// As you can't signal a thread directly, change the thread's
		// program counter to trigger an exception.
		CONTEXT cContext;
		cContext.ContextFlags = CONTEXT_CONTROL;
		::GetThreadContext(hThread, &cContext);

		// Set the program counter - this depends on the processor and
		// may be more complicated on some architectures.
		// Could pass a pointer to an exception raising routine.
		*--reinterpret_cast<DWORD*&>(cContext.Esp) = cContext.Eip;
		cContext.Eip = reinterpret_cast<DWORD>(RaiseThreadException);
		::SetThreadContext(hThread, &cContext);

		::ResumeThread(hThread);	// to its doom
	}

	AfxUnlockGlobals(CRIT_LOCKSHARED);
	_unlock(_TIME_LOCK);
	_unlock(_HEAP_LOCK);
}
Although we have used this code for several years it can be fragile and there have recently been reports of the program hanging at calls to WaitForSingleObject() immediately followin the call to this routine.

Is there a better way to do this? In particular is there a better way to unwind another thread’s stack?