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) } }
More Related questions...