Consider this scenario: a parking lot only contains a certain number of parking spaces, and only when there is space in the parking lot, the entry of the parking lot will open. C # provides the semaphore class to handle this scenario. The semaphore class can specify the number of resources during construction. The waitone method is used to wait for a resource and the release method is used to release a resource. Sample Code:
Using system;
Using system. Threading;
Namespace processtest
{
Class Program
{
Static semaphore;
Static void main (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 three resources
Semaphore = new semaphore (2, 5 );
// Enable three threads to compete for the remaining two resources
For (INT I = 0; I <3; I ++)
{
Thread t = new thread (New threadstart (workerproc ));
T. Name = "Thread" + I;
T. Start ();
Thread. Sleep (30 );
}
System. Console. readkey ();
}
Static void workerproc ()
{
For (INT I = 0; I <3; I ++)
{
// Wait for a resource Signal
Semaphore. waitone ();
Console. writeline (thread. currentthread. Name + ": Begin ");
Thread. Sleep (200 );
Console. writeline (thread. currentthread. Name + ": End ");
// Release resources
Semaphore. Release ();
}
}
}
}
The program first creates a semaphore class, which specifies that the number of resources is 5, but only two resources are released to compete with three threads. The other three resources are occupied by the main thread. The sub-thread first waits for a resource. After obtaining the resource, it sleeps for 200 ms and then releases the resource.
The output of this program is as follows: