.NET, C#, Programming Tutorial

C# Tutorial – Semaphore in action

Hi guys, today I’ll show you how to use semaphore in C# by an interesting sample.

Let’s imagine that some patients are in a clinic, there are two doctors and a security guard.

Each doctor can only examine one patient at a time. That means, at the clinic, there are only maximum 2 patients are examined at once. If anyone try to disturb the doctors will be prevented by the security guard.

When a patient is finished examining, another will be next.

OK, that is a situation in real, now, I’ll apply it to my C# code.

When a doctor is examining a patient, we can call it is a Thread.

Responsibility of the security guard seems like semaphore in C#

Let’s quote a short description from Microsoft about semaphore:

Limits the number of threads that can access a resource or pool of resources concurrently.

It’s really clear to understand, right? If not, you can visit the parent page of it to more learning.


And here, I only show you how to work with semaphore basically and clearly.

Let’s show the code bellow:

using System;
using System.Collections.Generic;
using System.Threading;

namespace SupperMaketUsingSemaphore
    class Program
        // The SDK clinic only have two doctors
        const int NumOfDoctors = 2;

        // And it also has a security guard
        static readonly Semaphore SecurityGuard = new Semaphore(NumOfDoctors, NumOfDoctors);

        // And there there are our patients who are waiting for examination
        static readonly List<string> Patients = new List<string> { "Peter", "Mary", "Mark", "Bill", "John", "Steve", "William" };

        // I don't know exactly how long the patients need to be examined
        static readonly Random ExaminationTime = new Random();

        static void Main()
            // Now, the doctors will help them to examine
            for (var i = 0; i < Patients.Count; i++)
                new Thread(DoExamine).Start(i);



        static void DoExamine(object patientIndex)
            // If there are two patients examining, the security guard will prevent the next patients

            Console.WriteLine(Patients[(int)patientIndex] + ", please!\n");

            // Patient need some time for payment
            Console.WriteLine(Patients[(int)patientIndex] + " is being examined\n");
            Thread.Sleep(ExaminationTime.Next(2000) + 2000);

            // Patient finished examination
            Console.WriteLine("Doctor: Thanks " + Patients[(int)patientIndex] + " for your cooperation\n");

            // The security is opening the door for Patient to leave the clinic

When we run the code, we’ll certainly see that there will have maximum two patients are examined at once.
We use

Semaphore SecurityGuard = new Semaphore(2, 2);

the second parameter tell that we only want two threads have permission to access to a block (this block will start with SecurityGuard.WaitOne() and end with SecurityGuard.Release())


when a thread try to access to some code and it’ll meet SecurityGuard.WaitOne() function, the semaphore object will count total number of threads are accessing within block, if the number is less than the maximum number allowed, the thread will be waited until another thread is released out of block by step out the SecurityGuard.Release(). Now, the thread which is trying to access this block will have permission to access this block.

OK, so far, I think everything is very clearly, try to run this code and see what happens is your part.

Happy coding!!


1 thought on “C# Tutorial – Semaphore in action”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s