Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any benefits of suspending a thread over making it wait?

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?

like image 275
Canopus Avatar asked Dec 14 '22 03:12

Canopus


2 Answers

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:

  • SuspendThread
  • Thread.Suspend
  • Thread.suspend

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.

like image 64
Kevin Montrose Avatar answered Feb 02 '23 01:02

Kevin Montrose


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.

like image 27
sharptooth Avatar answered Feb 01 '23 23:02

sharptooth