September 1, 2004

Why you should never call Suspend/TerminateThread (Part I)

Some people think that the usage of SuspendThread or TerminateThread is very useful.
But if you do this, you will get many, many problems…

You should NOT use Suspend/ResumeThread to do thread synchronization!
Mainly these functoions are pressent for debugging purpose. See MSDN documentation

See documentation for SuspendThread :

This function is primarily designed for use by debuggers It is not intended to be used for thread synchronization.

The documentation for TerminateThread is even worser!

If you use these function you can easily dead-lock your program. Here is just a simple example:


 #include <windows.h>
 #include <stdio.h>
 #include <process.h>
 unsigned __stdcall thread(void*)
 {
   while(1)
   {
     printf("t");
   }
 }
 int main()
 {
   unsigned dwThreadId;
   HANDLE hThread = (HANDLE) _beginthreadex(NULL, 0, thread, NULL, 0, &dwThreadId);
   while(1)
   {
     SuspendThread(hThread);
     printf(".");
     ResumeThread(hThread);
   }
   return 0;
 }

So please, never ever call Suspend/TerminateThread (expect if your write an debugger).


Posted 3 years, 5 months ago on September 1, 2004
The trackback url for this post is http://blog.kalmbachnet.de/bblog/trackback.php/6/

Re: Why you should never call Suspend/TerminateThread (Part I)
Hi, Jochen kalmbach! Nice to meet you again. Hcan the hThread exit? I don't see this sample explain the dead lock. Set this aside, then what's your alternative to these function ?
Posted 2 years, 10 months ago by youhua • @ • • Reply
Comment Trackback URL : http://blog.kalmbachnet.de/bblog/trackback.php/6/46/
Re: Why you should never call Suspend/TerminateThread (Part I)
Hi! In this example hThread does not exit... if I had made the example, so that hThread would exit, it will never exit because of the dead-lock! If you do not see the dead-lock, then please let it run! The problem is that "printf" internally uses a CriticalSection; and if the thread is suspsended while the CS is hold, the next call to printf in the main-thread will deadlock, because the thread is suspsended and therefor will never release the CS, because the main-thread waits until the CS will be released which will never happen... Alternatives: Use proper synchronisation objects
Posted 2 years, 10 months ago by Jochen Kalmbach • • • Reply
Comment Trackback URL : http://blog.kalmbachnet.de/bblog/trackback.php/6/47/

Comments have now been turned off for this post