Senior
What to say to the interviewer (if asked) "I would use a worker pool with a fixed number of workers, a channel for tasks, and a sync.WaitGroup. The workers will execute requests, and timeout and cancellation will be controlled through the context. I will collect the results in a slice, protected by a mutex (or through a separate channel)."} Now it's your turn Write the code in this chat. I will review and give feedback. If you don't know where to start – ask for a hint. Good luck!
sobes.tech AI
Answer from AI
go package main
import ( "context" "fmt" "sync" "time" )
// Task represents a task for processing type Task struct { id int // other fields }
// WorkerPool implements a pool of workers func WorkerPool(ctx context.Context, tasks <-chan Task, results chan<- string, wg *sync.WaitGroup) { defer wg.Done() for { select { case <-ctx.Done(): return case task, ok := <-tasks: if !ok { return } // Process task res := processTask(task) select { case results <- res: case <-ctx.Done(): return } } } }
func processTask(t Task) string { // simulate work time.Sleep(100 * time.Millisecond) return fmt.Sprintf("result for task %d", t.id) }
func main() { tasks := make(chan Task) results := make(chan string) var wg sync.WaitGroup
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
workerCount := 5
wg.Add(workerCount)
for i := 0; i < workerCount; i++ {
go WorkerPool(ctx, tasks, results, &wg)
}
// Separate goroutine to close results channel after workers finish
go func() {
wg.Wait()
close(results)
}()
// Send tasks
go func() {
for i := 0; i < 20; i++ {
tasks <- Task{id: i}
}
close(tasks)
}()
// Collect results
for res := range results {
fmt.Println(res)
}
}