0PricingLogin
Go Academy · Lesson

Semaphore Pattern

Limiting concurrency with a channel semaphore

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()
}

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