Semaphore is a class under system.threading that restricts the number of threads that can access a resource or resource pool at the same time.
Common construction methods
https://msdn.microsoft.com/zh-cn/library/e1hct27h (v=vs.110). aspx
Public Semaphore (int initialcount,int maximumcount)
Parameters
- Initialcount
-
Type: System.Int32
The number of initial requests for the semaphore that can be granted at the same time.
- Maximumcount
-
Type: System.Int32
The maximum number of requests for semaphores that can be granted at the same time.
Sample Code
classProgram {StaticSemaphore SEMA =NewSemaphore (1,1); Static voidMain (string[] args) { for(inti =0; I <3; i++) { varThread =NewThread (Test) {Name = $"thread{i}" }; Thread. Start (); } console.readkey (); } Static voidTest () {sema. WaitOne (); for(inti =0; I <3; i++) {Console.WriteLine ($"threadname:{Thread.CurrentThread.Name} i:{i}"); Thread.Sleep ( +); } sema. Release (); Console.readkey (); } }
Code Description:
static Semaphore sema = new Semaphore (n);
Declares a semaphore that indicates the initial and maximum number of thread concurrency for the controlled resource is 1
Sema. WaitOne ();
for (int i = 0; i < 3; i++)
{
Console.WriteLine ($ "threadname:{Thread.CurrentThread.Name} I:{i}");
Thread.Sleep (1000);
}
SEMA. Release ();
Using the above two methods to control resources, a thread executes SEMA. WaitOne () method, this method blocks until other threads are freed, called SEMA, if other threads are already consuming resources. Release (); method
The following results are performed:
During the same period of time, only one thread enters the shared resource.
The following are the execution effects with a maximum concurrency of 2:
static Semaphore sema = new Semaphore (2,2);
Over the same period of time, two threads have entered the contributing resource
Signal volume in C #---Semaphore