Junior — Middle
Can you explain what a semaphore is and how it is used to control access to resources?
sobes.tech AI
Answer from AI
A semaphore is a synchronization mechanism used to control access to a shared resource in multithreaded applications. It contains a counter that indicates how many threads can access the resource simultaneously.
Working principle:
- Initially, the counter is set to the number of available resources (for example, 3).
- When a thread wants to access, it calls the
Waitoperation (orWaitOnein C#), which decreases the counter by 1. - If the counter becomes less than zero, the thread is blocked and waits until the resource is released.
- When a thread releases the resource, it calls
Release, increasing the counter and unblocking waiting threads.
Example in C#:
using System;
using System.Threading;
class Program
{
static Semaphore semaphore = new Semaphore(3, 3); // maximum 3 threads simultaneously
static void AccessResource(int id)
{
Console.WriteLine($"Thread {id} is waiting for access");
semaphore.WaitOne(); // request access
Console.WriteLine($"Thread {id} has gained access");
Thread.Sleep(1000); // work with the resource
Console.WriteLine($"Thread {id} is releasing the resource");
semaphore.Release(); // release the resource
}
static void Main()
{
for (int i = 1; i <= 5; i++)
{
int localId = i;
new Thread(() => AccessResource(localId)).Start();
}
}
}
Thus, the semaphore limits the number of threads working with the resource simultaneously, preventing race conditions and ensuring correct operation.