Go Academy · Lesson

Semaphore Pattern

Limiting concurrency with a channel semaphore

Lesson 3 of 413 steps

Semaphore Pattern is a free Go Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

What is a semaphore?

A semaphore limits the number of goroutines performing an operation concurrently. It prevents resource exhaustion (e.g., too many open DB connections or outbound HTTP requests).

Buffered channel as semaphore

A buffered channel of capacity N acts as a counting semaphore. Acquiring sends to the channel (blocks when full); releasing receives from it.

sem := make(chan struct{}, 10)

func withSem(f func()) {
    sem <- struct{}{} // acquire
    defer func() { <-sem }() // release
    f()
}

Goroutine-per-job with semaphore

Spawn one goroutine per job but limit concurrency with a semaphore:

sem := make(chan struct{}, 5)
for _, job := range jobs {
    sem <- struct{}{}
    go func(j Job) {
        defer func() { <-sem }()
        process(j)
    }(job)
}

Draining the semaphore at end

After launching all goroutines, drain the semaphore to ensure all finish before returning:

// After the loop, acquire all N slots (blocks until all goroutines release)
for i := 0; i < cap(sem); i++ {
    sem <- struct{}{}
}

golang.org/x/sync/semaphore

For a weighted semaphore (e.g., goroutines with different resource weights), use the semaphore.Weighted type:

s := semaphore.NewWeighted(100)
// acquire 10 units
if err := s.Acquire(ctx, 10); err != nil { return err }
defer s.Release(10)
// do work

Context-aware acquire

The weighted semaphore's Acquire respects a context, returning an error if cancelled before the semaphore is available.

TryAcquire

s.TryAcquire(n) acquires n units only if they are immediately available, returning false otherwise. Useful for non-blocking checks.

Semaphore vs worker pool

A worker pool has a fixed set of persistent goroutines. A semaphore lets you spawn goroutines on demand but cap concurrency. Use a semaphore when job arrival rate varies widely.

HTTP concurrency limiting

Wrap an HTTP handler or client with a semaphore to prevent too many concurrent outbound requests or inbound handler goroutines.

Database connection limiting

Instead of a semaphore, set db.SetMaxOpenConns(n) and db.SetMaxIdleConns(m) — the sql package manages connection pool concurrency internally.

Semaphore fairness

Buffered channel semaphores are approximately fair (FIFO for goroutines blocked on send), but not strictly guaranteed. The weighted semaphore package provides stricter fairness guarantees.

Quick Check

How does a buffered channel implement a semaphore?

Recap: Semaphore Pattern

Key points:

  • Buffered channel sem := make(chan struct{}, N) for simple semaphores
  • Send to acquire; receive to release; always defer release
  • golang.org/x/sync/semaphore for weighted, context-aware variant
  • Use errgroup.SetLimit for simple per-group concurrency caps
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Semaphore Pattern” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Semaphore Pattern”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

What will I learn in “Semaphore Pattern”?

Limiting concurrency with a channel semaphore You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Semaphore Pattern” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Pipeline and Stage Patterns
  2. errgroup for Concurrent Error Handling
  3. Semaphore Pattern
  4. Leak Detection and Cancellation
← Back to Go Academy