Home > Article > Backend Development > Detailed explanation of the use of Semaphore in C# multi-threading
This article mainly introduces the usage of Semaphore in C# multi-threading in detail. It has certain reference value. Interested friends can refer to it
Semaphore: It can be understood as allowing threads to execute signals Pool, as many signals are put into the pool as many threads are allowed to execute at the same time.
private static void MultiThreadSynergicWithSemaphore() { //0表示创建Semaphore时,拥有可用信号量数值 //1表示Semaphore中,最多容纳信号量数值 Semaphore semaphore = new Semaphore(0, 1); Thread thread1 = new Thread(() => { //线程首先WaitOne等待一个可用的信号量 semaphore.WaitOne(); //在得到信号量后,执行下面代码内容 Console.WriteLine("thread1 work"); Thread.Sleep(5000); //线程执行完毕,将获得信号量释放(还给semaphore) semaphore.Release(); }); Thread thread2 = new Thread(() => { semaphore.WaitOne(); Console.WriteLine("thread2 work"); Thread.Sleep(5000); semaphore.Release(); }); thread2.Start(); thread1.Start(); //因在创建Semaphore时拥有的信号量为0 //semaphore.Release(1) 为加入1个信号量到semaphore中 semaphore.Release(1); }
Note:
1. If semaphore.Release(n), n>semaphore can accommodate the maximum semaphore, an exception will occur.
2. When the semaphore owned by semaphore is 1, Semaphore is equivalent to Mutex
3. When the semaphore owned by semaphore is >1, the number of semaphores is the number that can be obtained by multiple threads at the same time. , at this time it can be considered that the threads that have obtained the semaphore will be executed at the same time (the actual situation may be related to the number of CPU cores and the number of CPU simultaneous expenditure threads)
The above is the detailed content of Detailed explanation of the use of Semaphore in C# multi-threading. For more information, please follow other related articles on the PHP Chinese website!