C # Multithreading--Semaphore (Semaphore)

Source: Internet
Author: User
Tags semaphore

Baidu Encyclopedia : Semaphore, is responsible for coordinating the various threads to ensure that they can use public resources correctly and rationally. It is also the amount of the operating system that controls process synchronization mutex.

Semaphore commonly used methods have two WaitOne ( ) and release (),release () to exit the semaphore and return the previous count, while WaitOne () is blocking the current thread, Until the WaitHandle of the current thread receives a signal. Here I give an example to make it easier for everyone to understand: when we instantiate semaphore like this,

New Semaphore (
x
y
);

A queue of people in the bathroom, the equivalent of a thread, X is the number of positions remaining, Y is the total number of positions.

The WaitOne () method is equivalent to the person waiting for the toilet position behavior, and the release () method is equivalent to a person out of the toilet behavior, and then assume that X and Y are 5, the beginning of the toilet has 5 empty positions, and a total of only 5 positions, When a team of more than 5 people to go to the bathroom on the line, first WaitOne () method Wait, found that there is a vacancy in order to go in, each into a vacancy minus one, until the 5 after entering the empty space, then the people behind the wait until the people come out from the toilet Release () method, vacancy plus one, in the waiting for the WaitOne () method of the person found that there is a vacancy and enter a vacancy minus one ... So cyclical.

Take a look at the following example:

 Public classProgram {StaticSemaphore SEMA =NewSemaphore (5,5); Const intCyclenum =9; Static voidMain (string[] args) {             for(inti =0; i < Cyclenum; i++) {Thread TD=NewThread (NewParameterizedthreadstart (Testfun)); Td. Name=string. Format ("number {0}", i.ToString ()); Td. Start (TD.            Name);        } console.readkey (); }         Public Static voidTestfun (Objectobj) {Sema.            WaitOne (); Console.WriteLine (obj. ToString ()+"into the washroom:"+DateTime.Now.ToString ()); Thread.Sleep ( -); Console.WriteLine (obj. ToString ()+"out of the toilet:"+DateTime.Now.ToString ()); Sema.        Release (); }    }

The results of the operation are as follows:

Here I would like to point out that the semaphore control is only the amount of thread synchronization, regardless of the order, this example, thread control is the thread synchronization is 5, that is, the number of concurrent threads is 5, as to which is the first after which is not determined by the semaphore here .

Of course, in this example, because there is no complex operation, the general situation into the thread and the time of each thread will not be much different, so the order of execution is very regular (in order to illustrate this problem I also run several times to make the results slightly different, here number 2 Rob in the number 1 front is this truth), If there is a very complex operation in the thread that each thread is using in a different time, or if the loop is starting to have a complex operation then it is likely that it is not numbered 0 advanced into the toilet, and not necessarily the first entry will come out first.

Next, let's briefly introduce the overloaded methods of Semaphore's WaitOne () and release ()

 Public int Release (int releasecount);

Releasecount refers to the amount of semaphore released, if no parameter defaults to 1,release () is equivalent to release (1)

It is important to note that the semaphorefullexception exception is thrown when release () or release (int releasecount) executes, causing the semaphore count to be greater than the maximum number. The following situation is abnormal:

New Semaphore (4,5), SEM. Release (2);//Here is the release of 2 semaphores plus the previous 4, more than 5

 Public Virtual BOOL WaitOne (TimeSpan timeout);  Public Virtual BOOL WaitOne (int  millisecondstimeout);

First overloaded parameter timeout: Specifies the time interval, if no signal is received during this time, skips the wait to continue execution

Second overloaded parameter millisecondstimeout: Specifies the time interval integer milliseconds, if no signal is received during this time, skips the wait to continue execution

WaitOne () There are two overloaded methods that are not very common here is not introduced. The overloaded method above is no longer in the case of the example, interested friends can try it yourself.

According to the Seal sword White
Source: C # Multithreading--Semaphore (Semaphore)
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility. If you have any questions or suggestions, please enlighten me, thank you very much.

C # Multithreading--Semaphore (Semaphore)

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.