Senior
Tell me about the Semaphore pattern?
sobes.tech AI
Answer from AI
The Semaphore pattern is a synchronization mechanism that limits the number of operations executing simultaneously or access to a resource.
In Go, a semaphore can be implemented using a channel, limiting the number of goroutines that can execute a critical section at the same time.
Example of a simple semaphore in Go:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
sem := make(chan struct{}, 3) // semaphore with a capacity of 3
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
sem <- struct{}{} // acquire semaphore
fmt.Printf("Goroutine %d started work\n", id)
time.Sleep(1 * time.Second) // simulate work
fmt.Printf("Goroutine %d finished work\n", id)
<-sem // release semaphore
}(i)
}
wg.Wait()
}
In this example, no more than three goroutines can work simultaneously. Semaphores are useful for limiting parallelism, for example, when working with limited resources (connections, files, etc.).