Skip to content
GDP for Noobs
☰ All patterns
ConcurrencyIntermediate

Semaphore

Limit how many goroutines do something at the same time.

01

Explain it like I'm new

Real-life analogy

A nightclub bouncer

The club holds 3 people. The bouncer lets someone in only when someone else leaves. Everyone else waits in line.

😩 The problem

You start 1,000 goroutines that each hit an API allowing only 3 concurrent requests. You get rate-limited or crash the server.

💡 The pattern

Use a buffered channel with capacity N as a semaphore. Send a token to acquire (blocks when full) and receive to release.

02

Walk through the code

Click a step to highlight its lines. This is a complete program you can copy and run.

main.go
1package main
2
3import (
4 "fmt"
5 "sync"
6 "sync/atomic"
7 "time"
8)
9
10func main() {
11 const tasks, limit = 8, 3
12
13 // A buffered channel with room for `limit` tokens IS a semaphore.
14 sem := make(chan struct{}, limit)
15
16 var running, peak atomic.Int32
17 var wg sync.WaitGroup
18 for i := 1; i <= tasks; i++ {
19 wg.Add(1)
20 go func(id int) {
21 defer wg.Done()
22 sem <- struct{}{} // acquire: blocks if `limit` tasks are already running
23 defer func() { <-sem }() // release when done
24
25 now := running.Add(1)
26 for {
27 p := peak.Load()
28 if now <= p || peak.CompareAndSwap(p, now) {
29 break
30 }
31 }
32 time.Sleep(20 * time.Millisecond) // e.g. call a rate-limited API
33 running.Add(-1)
34 }(i)
35 }
36 wg.Wait()
37 fmt.Printf("ran %d tasks, at most %d at a time\n", tasks, limit)
38 fmt.Printf("peak concurrency observed: %d\n", peak.Load())
39 fmt.Println("limit respected?", peak.Load() <= limit)
40}
terminal
Press ▶ Run to execute this program.

This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.

03

When should I use it?

✅ Reach for it when…

  • •Rate-limited APIs, limited connections, memory-heavy tasks.

🚫 Skip it when…

  • •You also need a fixed set of reusable workers. A worker pool may be clearer.

🐹 Go tip

struct{} takes zero bytes, which makes it the idiomatic 'signal only' channel element.

🌍 You've already seen it in

golang.org/x/sync/semaphore (weighted) and errgroup.SetLimit use the same idea.

04

Quick check

One question. No pressure.

With `sem := make(chan struct{}, 3)`, what happens to the 4th goroutine that does `sem <- struct{}{}`?

Related: Worker Pool, Context Cancellation