Go Sync Semaphore
In this tutorial, you'll learn about Go Semaphore: Weighted vs Counting. We cover key concepts, practical examples, and best practices.
Weighted semaphore -- Use golang.org/x/sync/semaphore to limit concurrent access to resources.
The Problem
semaphore.Weighted provides a weighted semaphore with context support. Acquire blocks until weight is available. Release returns weight.
Wrong
for i := 0; i < 100; i++ {
go process(i) // All 100 run at once!
}
Output:
// Too many concurrent operations. Resource exhaustion.
Right
sema := semaphore.NewWeighted(10) // Max 10 concurrent
for i := 0; i < 100; i++ {
i := i
go func() {
sema.Acquire(ctx, 1)
defer sema.Release(1)
process(i)
}()
}
Output:
// Max 10 concurrent processes. Rest queued.
Prevention
- NewWeighted(max) sets concurrency limit
- Acquire blocks with context support
- TryAcquire for non-blocking attempt
- Release returns weight (1 or more)
- Weighted semaphore is more flexible than channel pool
Common Mistakes with sync semaphore
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro