Golang / GoLang Concurrency Mastery Interview Questions
Implement a bounded worker pool pattern in Go.
A worker pool limits the number of goroutines working concurrently, preventing resource exhaustion (file handles, DB connections, memory) when processing a large number of tasks. It is one of the most commonly asked Go patterns in technical interviews.
type Job struct { ID int; Payload string }
type Result struct { JobID int; Output string; Err error }
func workerPool(
ctx context.Context,
jobs <-chan Job,
numWorkers int,
) <-chan Result {
results := make(chan Result, numWorkers)
var wg sync.WaitGroup
wg.Add(numWorkers)
for w := 0; w < numWorkers; w++ {
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case job, ok := <-jobs:
if !ok { return } // channel closed — all work done
out, err := processJob(job)
select {
case results <- Result{job.ID, out, err}:
case <-ctx.Done(): return
}
}
}
}()
}
go func() { wg.Wait(); close(results) }()
return results
}
// Usage
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
jobs := make(chan Job, 100)
go func() {
defer close(jobs)
for i, item := range workItems {
select {
case jobs <- Job{ID: i, Payload: item}:
case <-ctx.Done(): return
}
}
}()
for r := range workerPool(ctx, jobs, runtime.NumCPU()) {
if r.Err != nil { log.Printf("job %d failed: %v", r.JobID, r.Err) }
}
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...
