A realization of the. Net signal Quantity (semaphore)

Source: Internet
Author: User
Tags assert bool count integer mutex reset resource thread

Motivation

Starting with the start of the contact multi-line programming model, learning is the synchronization primitives associated with semaphores (semaphore). I don't know why the. Net Framework has no corresponding stuff. It's killing me that I used to have a lot of tried-and-tested C + + code to achieve it, in order not to make the revolutionary martyrs of the drug free, blood white flow, had to give birth to one.

What is the semaphore (semaphore)

If you already know the concept of semaphore (semaphore), skip this paragraph.

Semaphore (semaphore) is a facility that is used in a multithreaded environment that coordinates threads to ensure that they can use public resources correctly and rationally.

Let's take a look at how a parking lot works. For simplicity's sake, let's say that there are only three parking spaces in the parking lot, and that three parking spaces are empty. This is if five cars come in at the same time, the doorman allows three of them to enter without hindrance, then puts down the car stop, the remaining car must wait at the entrance, thereafter the car also had to wait at the entrance. At this time, there is a car out of the car park, the doorman learned, open the car block, into a car, if you leave two, you can put two vehicles, so reciprocating.

In this parking system, parking is a public resource, each car is like a thread, the gatekeeper is the role of the signal.

Further, the characteristic of the semaphore is as follows: The semaphore is a nonnegative integer (number of parking spaces), and all the threads (vehicles) that pass through it subtract the integer (through it, of course, to use resources), and when the integer value is zero, all the threads attempting to pass it are in the waiting state. We define two kinds of operations on the semaphore: Wait (Waiting) and release (releasing). When a thread invokes a wait-waiting operation, it either passes the semaphore by one, or it waits until the semaphore is greater than one or times out. Release is actually a plus operation on the semaphore, corresponding to the vehicle leaving the car park, the operation is called "release" is the addition of the operation is actually released by the Semaphore Guardian resources.

Realize

As you all know, the thread synchronization facilities available in the. Net Framework class library include:

Monitor, AutoResetEvent, Manualresetevent,mutex,readwritelock and interlock. where AutoResetEvent, Manualresetevent,mutex derive from Waithandler, they actually encapsulate the kernel objects provided by the operating system. And the rest should be in. NET virtual machine in the native. Obviously the facilities from the OS kernel object are less efficient to use. But efficiency is not the problem we have to consider here, we will use two Monitor and a ManualResetEvent object to simulate a semaphore.

The code is as follows:

public class semaphore
{
Private ManualResetEvent waitevent = new ManualResetEvent (false);
Private Object syncobjwait = new Object ();
private int maxcount = 1; file://Maximum resource number
private int currentcount = 0; file://Current Resource Count

Public Semaphore ()
{

}

Public semaphore (int maxcount)
{
This.maxcount = Maxcount;
}

public bool Wait ()
{
Lock (syncobjwait) file://only one thread into the following code
{
BOOL Waitresult = This.waitEvent.WaitOne (); file://this waits for a resource number greater than 0
if (Waitresult)
{
Lock (This)
{
if (Currentcount > 0)
{
currentcount--;
if (currentcount = 0)
{
This.waitEvent.Reset ();
}

}
Else
{
System.Diagnostics.Debug.Assert (False, "Semaphore is isn't allow current count < 0");
}
}
}
return waitresult;
}
}

/**////<summary>
Allow wait operation returned by timeout
</summary>
<param name= "Millisecondstimeout" ></param>
<returns></returns>
public bool Wait (int millisecondstimeout)
{
Lock (syncobjwait)//Monitor ensures that the scope class code is in the critical area
{
BOOL Waitresult = This.waitEvent.WaitOne (Millisecondstimeout,false);
if (Waitresult)
{
Lock (This)
{
if (Currentcount > 0)
{
currentcount--;
if (currentcount = 0)
{
This.waitEvent.Reset ();
}

}
Else
{
System.Diagnostics.Debug.Assert (False, "Semaphore is isn't allow current count < 0");
}
}
}
return waitresult;
}
}


public bool Release ()
{
Lock (this)//Monitor ensures that the scope class code is in the critical area
{
currentcount++;
if (Currentcount > This.maxcount)
{
Currentcount = This.maxcount;
return false;
}
This.waitEvent.Set (); file://allow the thread that calls wait to enter
}
return true;
}

}



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.