I'm working on semaphore using C#. The following is my understanding about the Release
and WaitOne
methods in C#.
The WaitOne
method decreases the semaphore count when a thread enters a slot and when it leaves the slot, the semaphore is incremented.
The Release
method returns the previous semaphore count right? My understanding contradicts with the following code :
static Thread[] threads = new Thread[5];
static Semaphore sem = new Semaphore(3,5);
static void SemaphoreTest()
{
Console.WriteLine("{0} is waiting in line...", Thread.CurrentThread.Name);
Console.WriteLine("Semaphore count : "+sem.WaitOne());
Console.WriteLine("{0} enters the semaphore test", Thread.CurrentThread.Name);
Thread.Sleep(300);
Console.WriteLine("{0} is leaving the semaphore test and the semaphore count is {1}", Thread.CurrentThread.Name, sem.Release());
}
static void Main(string[] args)![enter image description here][2]
{
for (int i = 0; i < 5; i++)
{
threads[i] = new Thread(SemaphoreTest);
threads[i].Name = "thread_" + i;
threads[i].Start();
}
Console.Read();
Thread_2 leaves and hence the semaphore count must be incremented. But that is not happening as the previous semaphore count is 0 when thread_0 is about to leave. As per my understanding it must be one. Am I right? Could anyone explain this?