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)