Concept
Multiple threads using shared objects at the same time can cause a lot of problems, and synchronizing these threads makes it very important that the operations on the shared object be executed in the correct order, causing the problem of the race condition to be caused by the thread not synchronizing correctly. when a thread is using a shared resource, other threads should wait in turn, a common problem commonly referred to as thread synchronization.
More content
You should first try to avoid using a single object across multiple threads, eliminating complex synchronization constructs. If this is unavoidable, you can only use atomic operations. Once this operation is started, it runs until the end and is not interrupted by the thread scheduling mechanism. this avoids the use of locks and also avoids deadlocks.
If atomic operations are not feasible and the program logic is complex, we can only use different ways to coordinate threads. We can put the waiting thread in a blocking state, and the blocking state consumes as little CPU resources as possible, but this means that at least one context switch is present. Context switching means that the thread scheduler of the operating system saves the state of the waiting thread, switches to another thread, and finally resumes the state of the waiting thread, which consumes resources quite a lot. If a thread is suspended for a long time, it is worth it, which is known as kernel mode (kernel-mode), because only the kernel of the system can prevent threads from using CPU time.
But if the thread just needs to wait a little while, it's best to simply wait instead of blocking. While the thread waits for a wasted CPU time, it avoids the CPU time that is consumed by context switching, which becomes user mode (User-mode).
Note: This article is read in the "C # multithreaded Programming Combat" after the written, part of the content quoted the content of the book, this is a good book, thank you!
C # thread synchronization (ii)