Sobes.tech
Junior — Middle

What is the role of a semaphore in managing access to resources in multithreaded programming?

sobes.tech AI

Answer from AI

A semaphore in multithreaded programming is used to control access to limited resources. It contains a counter that indicates how many threads can access the resource simultaneously. When a thread wants to use the resource, it attempts to "acquire" the semaphore (decrease the counter). If the counter is greater than zero, the thread gains access; otherwise, it is blocked until the resource is released by another thread.

Example: if you have a pool of 3 database connections, a semaphore with a counter of 3 will allow no more than three threads to work simultaneously.

In Java, it looks like this:

Semaphore semaphore = new Semaphore(3);

try {
    semaphore.acquire(); // attempt to get permission
    // work with the resource
} finally {
    semaphore.release(); // release the permission
}
What is the role of a semaphore in managing access to… - sobes.tech