A detailed description of the use of C # multi-thread semaphore

Source: Internet
Author: User
This article is mainly for you to introduce in detail the C # multi-thread semaphore usage, with a certain reference value, interested in small partners can refer to

Semaphore: Can be understood as a pool that allows threads to execute signals, how many signals are placed in the pool and how many threads are allowed to execute simultaneously.


private static void Multithreadsynergicwithsemaphore ()  {   ///0 means that when the semaphore is created, it has the available semaphore value   //1 represents Semaphore, Accommodates up to a semaphore value   Semaphore Semaphore = new Semaphore (0, 1);   Thread thread1 = new Thread (() =    //thread first WaitOne waits for an available semaphore    semaphore. WaitOne ();    After obtaining the semaphore, execute the following code content    Console.WriteLine ("Thread1 work");    Thread.Sleep (the);    After the thread executes, it will get the semaphore release (back to Semaphore)    semaphore. Release ();   });   Thread thread2 = new Thread (() =   {    semaphore. WaitOne ();    Console.WriteLine ("Thread2 work");    Thread.Sleep (the);    Semaphore. Release ();   });   Thread2. Start ();   Thread1. Start ();   The semaphore is 0//semaphore when the semaphore is created   . Release (1) is semaphore to add 1 semaphores to Semaphore   . Release (1);  }

Description

1, if semaphore. Release (n), n>semaphore maximum capacity of the semaphore, will be abnormal.
2, when the semaphore has a semaphore of 1 o'clock, semaphore equivalent to a mutex
3, when the semaphore has a semaphore >1, the number of semaphores can be used by multiple threads simultaneously to obtain the number, At this point, the thread that gets the semaphore is considered to be executing concurrently (the actual number of CPU cores, CPU concurrent expenditure threads may be related)

Related Article

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.