C # multi-threaded programming: Use the semaphore class to limit the number of concurrent workers of resources

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.