Sobes.tech
Junior — Middle

What is the purpose of a semaphore in multithreaded applications?

sobes.tech AI

Answer from AI

A semaphore in multithreaded applications is used to control access to a limited number of resources.

It is a counter that indicates how many threads can access the resource simultaneously. When a thread wants to access, it attempts to "acquire" the semaphore:

  • If the counter is greater than zero, it is decremented by one, and the thread continues.
  • If the counter is zero, the thread is blocked until another thread releases the semaphore.

Example in Java:

import java.util.concurrent.Semaphore;

Semaphore semaphore = new Semaphore(3); // allow 3 threads simultaneously

try {
    semaphore.acquire(); // attempt to acquire permission
    // critical section
} catch (InterruptedException e) {
    e.printStackTrace();
} finally {
    semaphore.release(); // release permission
}

Thus, the semaphore helps control parallelism and prevent resource races.

What is the purpose of a semaphore in multithreaded… - sobes.tech