Are there any advantages to pausing a thread by making it wait?

I was looking at legacy code and found that the code uses the SuspendThread Function to pause the execution of a workflow. Whenever a worker thread needs to process a request, the calling thread resumes this worker thread. After the task completes, the thread pauses.

I do not know why this was done. In my opinion, this could be done more elegantly using the Event object with WaitForSingleObject API.

My question is, what are the advantages (if any) of thread suspension compared to having the thread wait on the synchronization object? In which scenarios do you prefer SuspendThread, ResumeThread APIs?

+4
source share
2 answers

No.

Pausing a thread is not recommended in every environment in which I have ever worked. The main problem is that the thread can be suspended while holding the lock on some resource, which can lead to blocking. Any resources saved in terms of synchronization objects are not worth the risk of deadlock.

This is not a concern when a thread waits for a wait, because the thread inherently controls its own “pause” and can be sure to release any locks it holds.

If you read the SuspendThread documentation, you will see that it is intended for use by debuggers. Extract it from any application code if you can.


To illustrate my point, a list of “do not use” pendants I've come across:

Aside; I am very surprised that .NET Thread.Suspend was "supported" in version 1.0 / 1.1, this really should have been a warning from the very beginning.

+11
source

For each thread, you will need a separate event object if you want to wake up a specific thread. This will lead to higher consumption of kernel objects, which in itself is not good and can cause problems with earlier versions of Windows. With a manual summary, you do not need any new kernel objects.

+2
source

All Articles