.NET thread synchronization in several ways

lock、Monitor:

Monitor the lock is syntactic sugar

 

[MethodImpl(MethodImplOptions.Synchronized)]:

A method of marking characteristics that need to be synchronized, and ultimately the effect of the use of the same lock keyword.

 

SpinLock:

Spin lock request when SpinLock enter the critical section, repeatedly rotate (empty execution cycle), until the lock becomes available. If the requested time is very short locks required, the idle provide better performance than blocked, because they do not change switch threads. However, if the locks held dozens of cycles or more, the SpinLock poor performance.

 

Mutex:

Mutex role is also to create a critical section to synchronize access to an object which, similar to the way the Monitor class, but the biggest difference is support for cross-process Mutex synchronization. Of course, its efficiency is not as Monitor, communications within the same process should first consider the use of Monitor.

 


Above all belong to an exclusive lock, and sometimes you do not need exclusive, can allow a certain number of concurrent threads to access a resource.

 

ReaderWriterLock、ReaderWriterLockSlim:

 It allows multiple threads to read a resource, but the writing to the thread waits for resource requirements to obtain an exclusive lock.

 

Semaphore、SemaphoreSlim:

 Semaphore class allows a specified number of threads to access a resource. When this number is exceeded, the resource request other threads will remain blocked until a thread releases the semaphore.

 


Notification: notification mechanism is a general term for all methods of waiting for the signal of another thread.

 

Join () method

 

AutoResetEvent, ManualResetEvent:

 

CountdownEvent: CountdownEvent Semaphore contrast with the action, provided Semaphore maximum number of available slots, when the count (i.e., when not enough resources) blocked thread is 0:00. The statistics used to CountdownEvent other end of the thread of the work, when the number of listeners to 0, the trigger signal.

 

Barrier: Barrier using class cycles can synchronize multiple threads, so that they are on the same point of a blocked waiting for other threads to complete.

 

Mutex class / Semaphore class: Both classes derived from WaitHandle, so they can be used with static methods of WaitHandle. For example, a thread can use a method WaitAll / WaitAny wait method, and the following three conditions are possible to unblock this thread: EventWaitHandle signal is received, the Mutex is released, Semaphore is released.

 

Reference: https://www.cnblogs.com/gjhjoy/p/3544361.html

Guess you like

Origin www.cnblogs.com/fanfan-90/p/12006965.html