Monday, December 5, 2011

Semaphore - Threading



Semaphore is similar to Lock and Mutex statements except it limits the number of concurrent thread can access the resource at a time. Using semaphore we can control how many thread can access resource at a time. The lock can be acquired using WaitOne method of Semaphore and can also be released using Release method of Semaphore. 


If Semaphore is named, it can be accessible throughout processes similar to Mutex. There is no guaranteed order in which blocked thread enters semaphore. Checkout Semaphore page on MSDN for more information.

In following example, five threads try to enter semaphore but at a time only three threads can enter.

public class MyClass
{
public static Semaphore semaphore = new Semaphore(3,3);
public static void DoWork(object i)
{
    Console.WriteLine("Thread {0} wants to enter", i.ToString());

    semaphore.WaitOne();

    Console.WriteLine("Thread {0} enters", i.ToString());

    Thread.Sleep(2000 * (int)i);

    Console.WriteLine("Thread {0} is leaving", i.ToString());

    semaphore.Release();
}
public static void Main()
{
    semaphore = new Semaphore(3, 3);
    for (int i = 1; i <= 5; i++)
    {
        Thread t1 = new Thread(new ParameterizedThreadStart(DoWork));
        t1.Start(i);
    }
}
}


As per above example, Semaphore instant created inside main method with limiting 3 threads. The loop creates five threads and tries to enter semaphore but semaphore only allows three threads at a time.


With Dotnet Framework 4.0, SemaphoreSlim class was introduced. This class is Optimized and faster than Semaphore. SemaphoreSlim was introduced specially for faster lock/release and for parallel programming.



No comments:

Post a Comment