Semaphore in thread

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.