C # multithreading 9-Semaphore,

Source: Internet
Author: User

C # multithreading 9-Semaphore,

Semaphore: it can be understood as a pool that allows threads to execute signals. The number of signals in the pool can be executed by multiple threads at the same time.

1 private static void MultiThreadSynergicWithSemaphore () 2 {3 // 0 indicates that when Semaphore is created, the available Semaphore value 4 // 1 indicates Semaphore, up to 5 Semaphore semaphore = new Semaphore (0, 1); 6 7 8 Thread thread1 = new Thread (() => 9 {10 // thread first WaitOne waits for an available semaphore 11 semaphore. waitOne (); 12 // after obtaining the semaphore, execute the following code content 13 Console. writeLine ("thread1 work"); 14 Thread. sleep (5000); 15 // After the thread is executed, the acquired semaphore is released (returned to semaphore) 16 semaphore. release (); 17}); 18 19 20 Thread thread2 = new Thread () => 21 {22 semaphore. waitOne (); 23 Console. writeLine ("thread2 work"); 24 Thread. sleep (5000); 25 semaphore. release (); 26}); 27 thread2.Start (); 28 thread1.Start (); 29 // The Semaphore generated when semaphore is created is 030 // Semaphore. release (1) adds one semaphore to 31 semaphore in semaphore. release (1); 32}

Note:

1. If semaphore. Release (n), n> semaphore holds the maximum semaphore, an exception occurs.
2. When semaphore has a Semaphore of 1, semaphore is equivalent to Mutex.
3. When semaphore has a semaphore greater than 1, the number of semaphores can be obtained by multiple threads at the same time, at this time, we can think that the thread that gets the semaphore will be executed simultaneously (the actual situation may be related to the number of CPU cores and the number of threads consumed at the same time by the CPU)

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.