A Semaphore is like a nightclub: it has a specific capacity (capacity) and is restricted by a guard. Once it is full, no one can go in again, and then a waiting Queue is formed outside ). Then, one person leaves and the first person in the Queue enters. This constructor requires at least two parameters: the available location in the nightclub and the capacity of the nightclub.
A semaphore with capacity is similar to a Mutex (Mutex) or lock, but semaphore does not have a "owner". In other words, it is unknown to a thread. Any thread can be called and released based on semaphore, but based on Mutex and lock, only the thread containing lock can be released.
There are two similar functions: Semaphore and SemaphoreSlim. The latter has been introduced and optimized in Framework4.0 to meet the low-latency (low latency) requirements in parallel programs. It is also useful in traditional multithreading because it allows you to specify a cancel mark while waiting. However, it cannot be used for sending signals between processes.
Semaphore requires only 1/4 microseconds to call WaitOne or Release.
Semaphore is useful in limiting concurrency-preventing too many threads from executing a specific code segment together. In the following example, five threads attempt to enter the nightclub, but the vegetation allows three threads at a time:
If the Sleep statement is replaced by the hard disk I/O (read/write) in the execution set, Semaphore will improve the execution efficiency by limiting excessive parallel hard disk drive processing activities.
A Semaphore, once named, can span processes like a Mutex.