0
0
CsharpConceptBeginner · 3 min read

Semaphore in C#: What It Is and How It Works

In C#, a Semaphore is a synchronization tool that controls how many threads can access a resource at the same time. It works like a traffic light, allowing a limited number of threads to enter a critical section while others wait.
⚙️

How It Works

Imagine a parking lot with a limited number of parking spaces. A Semaphore acts like the parking gate that only lets a certain number of cars in at once. When all spaces are full, new cars must wait until a space frees up.

In programming, this means a Semaphore keeps track of how many threads are currently using a resource. If the limit is reached, other threads pause until some threads finish and release their spot.

This helps prevent too many threads from running a part of code simultaneously, which could cause errors or slow down the program.

💻

Example

This example shows a Semaphore allowing only 2 threads to run a task at the same time. Other threads wait until a spot is free.

csharp
using System;
using System.Threading;

class Program
{
    static Semaphore semaphore = new Semaphore(2, 2); // max 2 threads

    static void AccessResource(object id)
    {
        Console.WriteLine($"Thread {id} is waiting to enter...");
        semaphore.WaitOne(); // request access

        Console.WriteLine($"Thread {id} has entered.");
        Thread.Sleep(2000); // simulate work

        Console.WriteLine($"Thread {id} is leaving.");
        semaphore.Release(); // release access
    }

    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            int threadId = i;
            new Thread(() => AccessResource(threadId)).Start();
        }
    }
}
Output
Thread 1 is waiting to enter... Thread 1 has entered. Thread 2 is waiting to enter... Thread 2 has entered. Thread 3 is waiting to enter... Thread 4 is waiting to enter... Thread 5 is waiting to enter... Thread 1 is leaving. Thread 3 has entered. Thread 2 is leaving. Thread 4 has entered. Thread 3 is leaving. Thread 5 has entered. Thread 4 is leaving. Thread 5 is leaving.
🎯

When to Use

Use a Semaphore when you want to limit how many threads can use a resource at the same time. This is helpful when the resource is limited, like a database connection or a file.

For example, if your program connects to a server that only allows 3 connections at once, a Semaphore can make sure no more than 3 threads try to connect simultaneously.

It also helps avoid crashes or slowdowns caused by too many threads running heavy tasks together.

Key Points

  • Semaphore controls access by counting available slots.
  • It blocks threads when the limit is reached.
  • Threads must release the semaphore after finishing.
  • Useful for managing limited resources safely.

Key Takeaways

Semaphore limits how many threads can access a resource at once.
Threads wait if the semaphore count is zero until a spot frees up.
Always release the semaphore after using the resource to avoid deadlocks.
Use semaphores to protect limited resources like connections or files.