Sunday, October 10, 2010

Multi threading and Semaphores in C#

using System;
using System.Threading;

class SemaphoreDemo
{
static Sempahore semaphore = new Semaphore(3,3);
public static void Main()
{
for(int i=0; i<10; i++)
{
new Thread(SemaphoreDemo.DoSomething).Start(i);
}
}
static void DoSomething(object id)
{
Console.WriteLine(id+" wants to access the semaphore");
semaphore.WaitOne();
Console.WriteLine(id+" has succeeded to access the semaphore");
Thread.Sleep(1000);
Console.WriteLine(id+" is about to leave the semaphore");
semaphore.Release();
}
}

No comments: