Post by Pavel A.Post by Martin B.Post by Andy SinclairPost by Martin B.Q: Is it safe to call TerminateThread from the thread itself?
TerminateThread seems to be generally considered evil, however I was
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
// ...
while( keep_running() ) {
// ...
if( terminate_immediately() ) {
fast_resource_cleanup();
::TerminateThread( GetCurrentThread(), 42 );
}
// ...
}
}
This doesn't really make sense as a concept.
As you are executing the thread you wish to exit, simply replace
'TerminateThread' with 'return 0'.
The use case I was thinking off was for a workaround to prevent
DLL_THREAD_DETACH from happening.
Have you considered DisableThreadLibraryCalls() instead?
Thanks for pointing out the function - I'm not sure if it's of any use
for me here.
My inital problem was that I needed to terminate+wait for a thread
during DLL unload[*] and I thought that when I'd signal the thread to
TerminateThread() itself I could actually wait for the thread. Since
AFAIK there is only one Loader Lock, DisableThreadLibraryCalls won't
help me much.
So, can anyone tell me if there is a technical reason why
::TerminateThread(self) should not be used? (Apart from the resulting
resource leaks in the DLLs that would expect a DLL_THREAD_DETACH)
cheers,
Martin
[*]: I know it's said it's a bad idea to wait for anything during Dll
unload in DllMain, but sometimes it's an option your temporarily have to
live with. (With ::ExitThread(self) waiting - if you have to do it - is
just a ::Sleep(long_enough) / with ::TerminateThread(self) I could
actually do a WaitForSingleObject.)