Repository navigation
Semaphores
- Semaphore Channel: A buffered channel with a capacity equal to the maximum number of concurrent accesses allowed.
- Acquire: Goroutines send a token to the semaphore channel before accessing the resource.
- Release: Goroutines receive a token from the semaphore channel after completing their task, freeing up space for other goroutines.
In Go, semaphores offer a way of controlling the number of goroutines that can be executing at any given time--just like worker pools. So what's the difference?
With a semaphore there's no need to manage channels for the workers yourself. Let's look at the example given from the golang.org/x/sync/semaphore package that we will use later in our exercise:
Source: https://pkg.go.dev/golang.org/x/sync/semaphore?tab=doc#example-package-WorkerPool
ctx := context.TODO()
var (
maxWorkers = runtime.GOMAXPROCS(0)
sem = semaphore.NewWeighted(int64(maxWorkers))
out = make([]int, 32)
)
// Compute the output using up to maxWorkers goroutines at a time.
for i := range out {
// When maxWorkers goroutines are in flight, Acquire blocks until one of the
// workers finishes.
if err := sem.Acquire(ctx, 1); err != nil {
log.Printf("Failed to acquire semaphore: %v", err)
break
}
go func(i int) {
defer sem.Release(1)
out[i] = collatzSteps(i + 1)
}(i)
}
// Acquire all of the tokens to wait for any remaining workers to finish.
//
// If you are already waiting for the workers by some other means (such as an
// errgroup.Group), you can omit this final Acquire call.
if err := sem.Acquire(ctx, int64(maxWorkers)); err != nil {
log.Printf("Failed to acquire semaphore: %v", err)
}In this exercise, you'll beging exploring useful patterns beyond the worker pool. Head on over.
Semaphores are a nice mechanism on their own but sometimes you need to control how long your program is allowed to run altogether. Just like in HTTP clients and servers, timeouts are a mechanism that prevent a resource from being exhausted simply because we never stop it. Building resilient systems and programs can often include mechanisms such as timeouts like we're about to show here.
When using semaphores, we can take advantage of the content.Context that their Acquire method accepts to control the maximum length of time allowed to acquire the semaphore.
func (s *Weighted) Acquire(ctx context.Context, n int64) errorBy coming up with a context.Context with a deadline attached to it, it becomes relatively simple to support semaphores with a timeout. Once the timeout elapses, the context cancellation will propagate through the semaphone and cause our program to stop.
Let's make use of context.Context! It's an excellense built-in mechanism to manage cancelations and timeouts in our programs and semaphores support it out of the box. Head on over.