Junior — Middle
What is the purpose of a semaphore mechanism in multithreaded programming?
sobes.tech AI
Answer from AI
A semaphore in multithreaded programming is used to control access to shared resources, limiting the number of threads that can use the resource simultaneously. It maintains a counter that decreases when a resource is acquired and increases when released. If the counter is zero, new threads are blocked until the resource is released.
Example in Go using a channel as a semaphore:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
sem := make(chan struct{}, 3) // semaphore with a maximum count of 3
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
sem <- struct{}{} // acquire resource
fmt.Printf("Goroutine %d started working\n", id)
// simulate work
// time.Sleep(time.Second)
fmt.Printf("Goroutine %d finished work\n", id)
<-sem // release resource
}(i)
}
wg.Wait()
}
Thus, a semaphore helps control concurrent access and prevents race conditions and resource overflow.