Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Terminate a hanging thread

0.00/5 (No votes)
25 Dec 2011CPOL1 min read 16.8K  
The right thing to do in this case is attach a debugger to determine the underlying cause of the the deadlock. This solution ignores the fact that the thread being terminated might have an exclusive lock on other critical resources (e.g., the OS loader lock or any application defined...
The right thing to do in this case is attach a debugger to determine the underlying cause of the the deadlock.

This solution ignores the fact that the thread being terminated might have an exclusive lock on other critical resources (e.g., the OS loader lock or any application defined synchronization object). For this reason, terminating a thread can work by happy accident in a lot of cases, but in general terminating a thread is inherently unsafe on the Windows platform.

For example, I encountered a deadlock that occurred due to calling WinVerifyTrust() from DllMain(). An undocumented feature of WinVerifyTrust() is that it can spawn a worker thread, which requires the OS loader lock ... and the OS loader lock was already acquired by the OS loader before the call to DllMain(). That's a classic deadlock. If we terminated the thread, then the underlying call would simply fail, which would ignore the underlying problem (illegal call from DllMain).

I have also encountered deadlocks in interprocess RPC where the lock order of various synchronization objects was random between different processes and threads, which can result in more complex deadlocks. Again, terminating the thread would simply cause the RPC to fail, and not address the real problem (undefined lock order).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)