I was going through a legacy code and found that the code uses SuspendThread Function to suspend the execution of a worker thread. Whenever the worker thread needs to process a request, the calling thread resumes this worker thread. Once the task is done the thread suspends itself.
I don’t know why it was done this way. According to me it could have been done more elegantly using an Event object with WaitForSingleObject API.
My question is, what are the benefits (if any) of suspending a thread as compared to making a thread wait on a synchronization object? In which scenarios would you prefer SuspendThread, ResumeThread APIs?
No.
Suspending a thread is discouraged in every environment I've ever worked in. The main concern is that a thread may be suspended while holding onto a lock on some resource, potentially causing a dead lock. Any resources saved in terms of synchronization objects aren't worth the deadlock risks.
This is not a concern when a thread is made to wait, as the thread inherently controls its own "suspension" and can be sure to release any locks it is holding.
If you read the documentation on SuspendThread, you'll see that it is meant for use by debuggers. Tear it out of any application code if you can.
To illustrate my point, a list of the "do not use" suspension methods I've come across:
As an aside; I'm really surprised that Thread.Suspend in .NET was "supported" in 1.0/1.1, it really should have been warning worthy from the start.
You'll need a separate event object for each thread if you want to be able to wake up a specific thread. That would lead to higher kernel object consumption which is not good by itself and could possibly cause problems on early versions of Windows. With manual resume you don't need any new kernel objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With