Semaphore inherits from WaitHandle.
The semaphore says that the simple point is for thread synchronization, or to limit the number of threads that can run.
Create a Restricted resource class //resource number of 5, open resources 2 ///main thread automatically occupies 3 resources semaphore = new Semaphore (2, 5);
So how does it limit the number of threads to a mile? Because there is a counter inside it, such as you want to limit up to 5 threads to run, then the value of this counter will be set to 5, if a thread calls this semaphore, then its counter will be reduced by 1, until the counter becomes 0. At this point, if another thread continues to invoke the semaphore, the thread will be blocked (the counter is reduced by 1 per WaitOne () method call).
After getting the semaphore thread to handle its logic, you can call its release () or release (1) function to add 1 to its counter so that other blocked threads can be called .
Full codes:
classSemaphoredemo {StaticSemaphore Semaphore; Static voidMain (string[] args) { //Create a restricted resource class//The number of resources is 5, and the number of open resources is 2//The main thread automatically occupies 3 resourcessemaphore =NewSemaphore (2,5); //Open 3 threads and let them compete for the remaining 2 resources for(inti =0; I <3; i++) {Thread T=NewThread (NewParameterizedthreadstart (Workerproc)); T.name="Thread"+i; T.start (T.name); } System.Console.ReadKey (); } Static voidworkerproc (Object obj) {Console.WriteLine (string. Format ("thread: {0} ready to execute", obj)); Semaphore. WaitOne (); Console.WriteLine (string. Format ("thread: {0} starts execution, stays for 5 seconds", obj)); Thread.Sleep ( the); Console.WriteLine (string. Format ("thread: {0} execution ended, release semaphore", obj)); Semaphore. Release (); }
"Deep Good text" multi-thread waithandle--> derivation-"semaphore signal volume construction