Semaphores
Definition
Semaphore
- In plain English
- A semaphore is a counter that allows up to N goroutines into a section at the same time.
- Think of it like
- It is like a car park barrier that only lifts while spaces remain.
Why it exists
Starting 500 audio conversions together can exhaust memory. Only four should use the expensive encoder at once.
An insurer permits ten concurrent calls. Hold a slot for the entire call, then release it.
Token
- In plain English
- A token is an empty channel value representing one occupied semaphore slot.
- Think of it like
- Like a numbered ticket showing one space is in use.
context
- In plain English
- A context carries a cancellation signal and an optional deadline that every goroutine in a piece of work can watch.
- Think of it like
- It is like a fire alarm that tells everyone in the building to stop and leave.
How it works
Rate of concurrency vs rate limit
- In plain English
- Limiting concurrency caps how many tasks run at once, while a rate limit caps how many start per second.
- Think of it like
- Like a restaurant's table count versus how many guests the door lets in per minute.
- Acquire
Send one token before starting a goroutine, so waiting jobs do not each need their own goroutine.
- Release
Defer receiving that token back when the operation ends.
- Wait
Wait for every started goroutine before returning.
Tasks enter Four slots before Working, which sends a release back to Four slots.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
sem := make(chan struct{}, 4)
var wg sync.WaitGroup
for id := 1; id <= 8; id++ {
sem <- struct{}{}
wg.Add(1)
go func(id int) {
defer wg.Done()
defer func() { <-sem }()
time.Sleep(10 * time.Millisecond)
fmt.Println("transcode", id)
}(id)
}
wg.Wait()
}
Weighted permits
- In plain English
- Weighted permits let one operation reserve several semaphore slots at once.
- Think of it like
- Like a large vehicle taking two spaces.
// Import golang.org/x/sync/semaphore in the surrounding file.
sem := semaphore.NewWeighted(4)
if err := sem.Acquire(ctx, 2); err != nil {
return err
}
defer sem.Release(2)
// Work holds two of the four permits.
Examples
Cap expensive conversions
Eight episodes need conversion. Four encoder slots bound the expensive work.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
sem := make(chan struct{}, 4)
var wg sync.WaitGroup
for id := 1; id <= 8; id++ {
sem <- struct{}{}
wg.Add(1)
go func(id int) {
defer wg.Done()
defer func() { <-sem }()
time.Sleep(10 * time.Millisecond)
fmt.Println("transcode", id)
}(id)
}
wg.Wait()
}
Output order can vary. Acquiring before go also bounds the number of running helpers.
The insight
A buffered channel of size N can act as a semaphore.
Share six connectors
Seven cars request six connectors. The seventh waits until a charging operation releases a slot.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
sem := make(chan struct{}, 6)
var wg sync.WaitGroup
for id := 1; id <= 7; id++ {
sem <- struct{}{}
wg.Add(1)
go func(id int) {
defer wg.Done()
defer func() { <-sem }()
time.Sleep(10 * time.Millisecond)
fmt.Println("charge", id)
}(id)
}
wg.Wait()
}
This models connector use only. It does not promise a particular waiting order.
The insight
Semaphores also model limited physical resources.
Respect insurer concurrency
Twelve refills need insurer calls. At most ten calls may be active.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
sem := make(chan struct{}, 10)
var wg sync.WaitGroup
for id := 1; id <= 12; id++ {
sem <- struct{}{}
wg.Add(1)
go func(id int) {
defer wg.Done()
defer func() { <-sem }()
time.Sleep(10 * time.Millisecond)
fmt.Println("insurer call", id)
}(id)
}
wg.Wait()
}
A separate requests-per-second restriction needs another mechanism. The semaphore controls active calls only.
The insight
Protect partners' concurrency limits as well as your own memory.
Trade-offs
Pros
- Bound expensive active work.
- Respect downstream concurrency limits.
Cons
- Missing releases permanently consume slots.
- Requests per second remain unbounded.
Use when
- Work uses scarce resources.
- A service caps simultaneous calls.
Avoid when
- Coordination costs more than the work.
- A per-second limit is the actual requirement.
Quick check
Takeaways
- A semaphore caps active operations at N.
- A buffered channel can hold semaphore tokens.
- Always release acquired tokens with defer.