Thread Synchronization with SemaphoreSlim Construct

What is SemaphoreSlim and how to synchronize threads using SemaphoreSlim

Category: Multithreading Tags: C#


        We use semaphore construct to limit concurrent threads which can access a resource if threads trying to access a resource are more than declared limit only limited threads will be granted access and others will have to wait.


        To understand SemaphoreSlim observe code below:

class Program
    //only 3 threads can access resource simulteniously
    static SemaphoreSlim semaphore = new SemaphoreSlim(3);
    static void Main(string[] args)
        for (int i = 1; i <= 5; i++)
            int count = i;
            Thread t = new Thread(() => SemaphoreFun("thread " + count, 1000 * count));

    static void SemaphoreFun(string name, int seconds)
        Console.WriteLine("{0} Waits to access resource", name);
        Console.WriteLine("{0} was granted access to resource", name);

        Console.WriteLine("{0} is completed", name);

Above code we can see we have a Function called SemaphoreFun which gives access to a resource, Wait method blocks current thread until it can access resource and Release method is required to release a resource once work is done. To understand we created five threads in Main thread which try to access SemaphoreFun simultaneously but we limited the access to three using SemaphoreSlim object. When we run above code we will get output like:

thread 3 Waits to access resource
thread 2 Waits to access resource
thread 2 was granted access to resource
thread 1 Waits to access resource
thread 1 was granted access to resource
thread 3 was granted access to resource
thread 5 Waits to access resource
thread 4 Waits to access resource
thread 1 is completed
thread 5 was granted access to resource
thread 2 is completed
thread 4 was granted access to resource
thread 3 is completed
thread 4 is completed
thread 5 is completed

There is an old version of SemaphoreSlim which is Semaphore, Semaphore can be used as we used Mutex construct making it named Mutex construct in our last article. Samephore uses windows kernel for scheduling.

Like 0 People
Last modified on 11 October 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 126
Questions: 9
Given Best Solutions: 8 *


No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User