Why we don’t recommend suspending a thread

Pausing the thread is a bad idea

Suspend a thread is as bad as Terminate a thread.
I am not going to answer this question directly. I am going to ask you some questions first and then see what your answer is?

Consider the following C# code:

 

When you try to run this program and click the Enter button, the program will hang. But if you modify the code in the worker thread as follows:
for (;;) {} the
program can run smoothly, what is going on?

In the worker thread, most of the CPU time is used to execute System.Console.WriteLine, so when you execute Thread.Suspend(), the worker thread will most likely stay in the System.Console.WriteLine code.

Question: So, is the implementation of System.Console.WriteLine thread-safe?

Answer: Yes, it is thread-safe, I can be sure of this without even looking at the relevant documentation. The main program does not do any thread synchronization, but directly calls it from two different threads. Therefore, it is best to be thread-safe, otherwise we will be in big trouble before we encounter the thread suspension problem.

Question: How should a thread safety mechanism be imposed on an object?

Question: When a thread-safe code is running, what happens if the thread is suspended at this time?

Question: What happens if you access the same object in another thread?

Answer: The question mentioned above is a general question, not limited to C# language. For Win32 or any threading model, there is the same logic.
In Win32, the processor heap memory is a thread-safe object, because in a Win32 program, if the heap memory cannot be accessed flexibly and conveniently, the Win32 program basically cannot do much. It is very possible to suspend a thread in Win32. Will cause a deadlock in the process.

If this is the case, then why implement the SuspendThread API?
Mainly to consider the scenario of using the debugger.
When we use the debugger to debug a program, the debugger will use this API to suspend all threads in the process. Sometimes the debugger will also be used to suspend other threads, so that you can focus on a single thread at a time. Receive interference from other threads running.
Because the debugger is in a separate process, all this behavior will not cause a deadlock.

to sum up

Some Win32 APIs, if you do not understand the principles and applicable scenarios, it is best not to use them.
What if you fall into the ditch again?

Guess you like

Origin blog.csdn.net/mmxida/article/details/108112210