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)