Sobes.tech
Junior — Middle

In what scenarios is the Semaphore mechanism used for thread or process synchronization?

sobes.tech AI

Answer from AI

The Semaphore mechanism is used to control access to a limited number of resources in multithreaded or multiprocess applications. It allows limiting the number of threads that can simultaneously execute a certain section of code or use a resource.

Use cases:

  • Limiting the number of concurrent database connections.
  • Controlling access to a thread or connection pool.
  • Synchronizing threads when performing tasks where only a fixed number of executors can work at the same time.

Example in Go:

var sem = make(chan struct{}, 3) // maximum 3 concurrent accesses

func worker(id int) {
    sem <- struct{}{} // acquire semaphore
    fmt.Printf("Worker %d started\n", id)
    time.Sleep(time.Second) // work
    fmt.Printf("Worker %d finished\n", id)
    <-sem // release semaphore
}

func main() {
    for i := 0; i < 10; i++ {
        go worker(i)
    }
    time.Sleep(5 * time.Second)
}

In this example, no more than 3 goroutines perform work simultaneously.

In what scenarios is the Semaphore mechanism used for… - sobes.tech