Middle+
// Task: implement workerPool // numWorkers – number of workers // jobs – list of numbers to process // Each worker squares the number // Return all results (order does not matter) func workerPool(numWorkers int, jobs []int) []int { // your code here }
sobes.tech AI
Answer from AI
go func workerPool(numWorkers int, jobs []int) []int { type jobResult struct { result int }
jobsCh := make(chan int, len(jobs))
resultsCh := make(chan int, len(jobs))
// Launch workers
for i := 0; i < numWorkers; i++ {
go func() {
for job := range jobsCh {
resultsCh <- job * job
}
}()
}
// Send jobs
for _, job := range jobs {
jobsCh <- job
}
close(jobsCh)
// Collect results
results := make([]int, 0, len(jobs))
for i := 0; i < len(jobs); i++ {
results = append(results, <-resultsCh)
}
return results
}