0Pricing
Go Academy · Lesson

Semaphore Pattern

Limiting concurrency with a channel semaphore

Semaphore Pattern is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

Frequently asked questions

Is the “Semaphore Pattern” lesson free?

Yes — the full text of “Semaphore Pattern” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

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