Thread synchronization

When one thread performs increment and decrement operations, the other threads must wait for their turn. Organizing threads in such a way is often referred to as thread synchronization.


There are several ways to achieve thread synchronization.

1. if there is no shared object, there is no need for synchronization at all.

    - remove complex synchronization constructs, a shared state, or avoid using a single object from several threads.

2.If we must have a shared state, the second approach is to use only atomic operations.

This means that an operation takes a single quantum of time and completes at once, so no other
thread can perform another operation until the first operation is complete. Therefore, there is
no need to make other threads wait for this operation to complete and there is no need to use
locks; this in turn, excludes the deadlock situation.

 

3. If this is not possible and the program's logic is more complicated, then we have to use
different constructs to coordinate threads.

 [kernel-mode constructs]

 One group of these constructs puts a waiting thread into a blocked state. In a blocked state, a thread uses as little CPU time as possible.
However, this means that it will include at least one so-called context switch—the thread
scheduler of an operating system will save the waiting thread's state and switch to another
thread, restoring its state by turn. This takes a considerable amount of resources; however,
if the thread is going to be suspended for a long time, it is good. These kind of constructs
are also called kernel-mode constructs because only the kernel of an operating system is
able to stop a thread from using CPU time.

[user-mode constructs]

In case, we have to wait for a short period of time, it is better to simply wait than switch
the thread to a blocked state. This will save us the context switch at the cost of some
wasted CPU time while the thread is waiting. Such constructs are referred to as user-mode
constructs. They are very lightweight and fast, but they waste a lot of CPU time in case a
thread has to wait for long.

[hybrid constructs]
To use the best of both worlds, there are hybrid constructs; these try to use user-mode
waiting first, and then, if a thread waits long enough, it switches to the blocked state,
saving CPU resources.

 

  a.Interlocked construct.

  b.Mutex construct

  c.SemaphoreSlim construct

 

From: Multithreading with C# Cookbook 2nd - Eugene Agafonov

 

posted @ 2021-03-16 14:34  blogger2020  阅读(43)  评论(0)    收藏  举报