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)
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
