C# by Mike

How to Implement Thread Synchronization using Semaphore

Semaphore is mainly used in scenarios where we have a limited number of resources and we have to limit the number of threads that can use it. The semaphore class lets you limit the number of threads accessing a critical section.

Semaphores are Int32 variables stored in an operating system's resources. When we initialize the semaphore object, we initialize it with a number. This number limits the threads that can enter the critical section.

For using a semaphore in C#, you just need to instantiate an instance of a Semaphore object. 

public static class SemaphoreSample
{
    public static void Execute()
    {
        for (int i = 0; i < 5; i++)
        {
            Thread doWorkThread = new Thread(new ParameterizedThreadStart(doWork));

            doWorkThread.Start(i);
        }

        Console.ReadLine();
    }

    //A semaphore is very similar to lock/Monitor. The difference is that it can allow for a specified amount of threads to work with the same resources at the same time.
    //Make a semaphore that allows for up to two threads to work with the same resource. 
    private static Semaphore semaphore = new Semaphore(1, 1); //Semaphore(initial thread count, max thread count)

    private static void doWork(object threadNumber)
    {
        try
        {
            //The code will stop executing here and wait until the lock is released by the previous thread. 
            semaphore.WaitOne();

            Console.WriteLine("Thread " + threadNumber.ToString() + " has started.");

            //Simulate doing time consuming work.
            Thread.Sleep(1500);

            Console.WriteLine("Thread " + threadNumber.ToString() + " is done.");
        }
        finally
        {
            //Realesase the lock so other threads can now get access.
            semaphore.Release();
        }
    }
}
Semaphore

Comments