Golang / GoLang Concurrency Mastery Interview Questions
How do you use a buffered channel as a semaphore to limit goroutine concurrency?
A buffered channel of capacity N acts as a counting semaphore — at most N goroutines can be in a critical section simultaneously. This is a simple, idiomatic Go pattern for throttling concurrent HTTP requests, database queries, or any resource-bounded operation.
// Semaphore: limit to 10 concurrent HTTP fetches func fetchAll(ctx context.Context, urls []string) []string { const maxConcurrent = 10 sem := make(chan struct{}, maxConcurrent) results := make([]string, len(urls)) var wg sync.WaitGroup for i, url := range urls { wg.Add(1) go func(idx int, u string) { defer wg.Done() // Acquire a slot (blocks if 10 goroutines are already running) select { case sem <- struct{}{}: case <-ctx.Done(): return } defer func() { <-sem }() // release slot on exit results[idx] = fetch(ctx, u) }(i, url) } wg.Wait() return results } // Why struct{} and not bool or int? // struct{} is zero-size â no memory allocated for the value itself // golang.org/x/sync/semaphore: weighted semaphore for varying costs sem := semaphore.NewWeighted(10) if err := sem.Acquire(ctx, 1); err != nil { return err } defer sem.Release(1)
More Related questions...