Scene: hard-to-avoid concurrent access to certain limited resources when multiple tasks or threads are running in parallel
You might consider using semaphores to do this control (System.Threading.Semaphore) is a semaphore object that represents a Windows kernel (operating system level, which can span processes or appdomain). If the expected wait time is short, the overhead of using Semaphoreslim (single process) is less. The difference between the two is as follows:
The System.Threading.Semaphore class represents a named (System-wide) or local semaphore. It is a thin wrapper around the Win32 semaphore object. The Win32 Semaphore is a count semaphore that can be used to control access to a resource pool.
Semaphoreslimclass represents a lightweight, fast semaphore that can be used to wait within a single process when the wait time is expected to be short.semaphoreslim relies as much as possible on synchronization primitives provided by the common Lang Uage Runtime (CLR). > semaphoreslim relies as much as possible on synchronization primitives provided by the common language runtime (CLR). But it also provides deferred initialization, kernel-based wait handles, as necessary support for waiting on multiple semaphores. semaphoreslim also supports the use of cancellation tokens, but it does no support named Semaphor Es or the use of a wait handle for synchronization. " > semaphoreslim also supports the use of cancellation tokens, but does not support named semaphores or uses a wait handle for synchronization.
Here we only discuss the amount of semaphores in the System.threading.semaphore,.net framework to coordinate access to resources by tracking the tasks or threads that enter and leave. The number of beacons needs to know the maximum number of resources, when a task enters, the resource counter will be reduced by 1 (Get access License), when the counter is 0 o'clock, if there is a task access to the resource (not authorized access License), it will be blocked until a task left .
Introduce the commonly used initialization constructs of the semaphore class, as below, and read the comments section carefully.
// <summary> ///Initializes a new instance of the<see cref= "T:System.Threading.Semaphore"/>class, specifying the maximum number of concurrent entries and optionally reserving some entries. /// </summary> /// <param name= "Initialcount" >The initial number of requests for the semaphore so can be granted concurrently.</param><param name= "Maximumcount" >The maximum number of requests for the semaphore so can be granted concurrently.</param><exception cref= "T:System.ArgumentException" ><paramref name= "InitialCount"/>is greater than<paramref name= "Maximumcount"/>.</exception><exception cref= "T:System.ArgumentOutOfRangeException" ><paramref name= " Maximumcount "/>is less than 1.-or-<paramref name= "Initialcount"/>is less than 0.</exception>[SecuritySafeCritical] [Targetedpatchingoptout ("performance critical to-inline this type of method across NGen image boundaries")] PublicSemaphore (intInitialcount,intMaximumcount);
Initialcount: The initial value of the amount of concurrent requests that the semaphore can accept
Maximumcount: Maximum number of concurrent requests that the semaphore can accept
So look at the demo below.
1 class Program2 {3 //create a semaphore that can authorize 2 licenses with an initial value of 24 StaticSemaphore _semaphore =NewSemaphore (2,2);5 6 Static voidMain (string[] args)7 {8Task.Factory.StartNew (() =DoWork ());9Task.Factory.StartNew (() =DoWork ());TenTask.Factory.StartNew (() =DoWork ()); One A console.readline (); - } - the Static voidDoWork () - { - Try - { +Console.WriteLine (string. Format ("Thread {0} is waiting for a license ...", Thread.CurrentThread.ManagedThreadId)); - _semaphore. WaitOne (); +Console.WriteLine (string. Format ("Thread {0} applied to license ...", Thread.CurrentThread.ManagedThreadId)); AThread.Sleep ( the); atConsole.WriteLine (string. Format ("Thread {0} release license ...", Thread.CurrentThread.ManagedThreadId)); - } - finally - { - _semaphore. Release (); - } in } -}View Code
Multiple threads request to obtain a license, where thread a passes _semaphore. WaitOne got a license for initialCount-1 operation and then called _semaphore after the business was completed. Release released this license, Initialcount+1. If you set the maximum concurrency = 1, only 1 threads are currently able to get this permission, and the other threads are blocked until the thread is released. Of course, the semaphore cannot be permanently blocked there. The semaphore also provides a timeout processing mechanism. The method is to pass in the wait function a timeout wait time-wait (int timeout). When the wait return value is False, it indicates that it timed out. If 1 is passed in, it indicates an indefinite wait.
About semaphores and lock/queue concepts
The semaphore (Semaphore), sometimes called a semaphore, is a facility used in a multithreaded environment and is used by the operating system to control waiting for a mechanism which coordinates the various threads to ensure that they are able to use public resources correctly and rationally.
Mutex (mutex), the data structure of mutual exclusion, is also considered as a two-yuan semaphore. A mutex is basically a multitasking-sensitive two-dollar signal that can be used as a synchronous multitasking behavior, and it is commonly used as a resource to protect critical segment code from interrupts and to use it in shared synchronization.
A mutex is essentially a lock that provides exclusive access to a resource, so the main purpose of the mutex is to use mutex. The value of a mutex object, with only 0 and 12 values. These two values also represent the two states of the mutex, respectively. A value of 0 indicates a locked state, the current object is locked, and the user process/thread enters a queued wait if it tries to lock a critical resource, a value of 1 indicates an idle state, the current object is idle, the user process/thread can lock the critical resource, and then the mutex value is reduced by 1 to 0.
Enqueue and lock are actually two names of a thing. They all support queue and concurrency (concurrency). They are managed in the queue in a "FIFO" manner.
Semaphore (semaphore)