Semaphore in C#


The semaphore class lets you set a limit on the number of threads that have access to a critical section. The class is used to control access to a pool of resources. System.Threading.Semaphore is the namespace for Semaphore because it has all the methods and properties required to implement Semaphore.

For using a semaphore in C#, you just need to instantiate an instance of a Semaphore object. It has minimum of two arguments −

Reference

MSDN

Sr.No.Constructor & Description
1Semaphore(Int32,Int32)
Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries.
2Semaphore(Int32,Int32,String) −
Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, and optionally specifying the name of a system semaphore object.
3Semaphore(Int32,Int32,String,Boolean)
Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, and specifying a variable that receives a value indicating whether a new system semaphore was created.

Let us now see an example:

Here, we have used the following Semaphore constructor that initializes a new instance of the Semaphore class, specifying the maximum number of concurrent entries and optionally reserving some entries.

static Semaphore semaphore = new Semaphore(2, 2);

Example

 Live Demo

using System;
using System.Threading;
namespace Program
{
class Demo
   {
      static Thread[] t = new Thread[5];
      static Semaphore semaphore = new Semaphore(2, 2);
      static void DoSomething()
      {
         Console.WriteLine("{0} = waiting", Thread.CurrentThread.Name);
         semaphore.WaitOne();
         Console.WriteLine("{0} begins!", Thread.CurrentThread.Name);
         Thread.Sleep(1000);
         Console.WriteLine("{0} releasing...", Thread.CurrentThread.Name);
         semaphore.Release();
      }
      static void Main(string[] args)
      {
         for (int j = 0; j < 5; j++)
         {
            t[j] = new Thread(DoSomething);
            t[j].Name = "thread number " + j;
            t[j].Start();
         }
         Console.Read();
      }
   }
}

Output

The following is the output

thread number 2 = waiting
thread number 0 = waiting
thread number 3 = waiting
thread number 1 = waiting
thread number 4 = waiting
thread number 2 begins!
thread number 1 begins!
thread number 2 releasing...
thread number 1 releasing...
thread number 4 begins!
thread number 3 begins!
thread number 4 releasing...
thread number 0 begins!
thread number 3 releasing...
thread number 0 releasing...

Updated on: 01-Apr-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements