Go
Beginner
1 min read
Worker Pools with Channels
Example
package main
import (
"fmt"
"sync"
"time"
)
type Job struct {
ID int
Input int
}
type Result struct {
Job Job
Output int
}
func worker(id int, jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
// Simulate CPU-bound work
time.Sleep(10 * time.Millisecond)
output := job.Input * job.Input
fmt.Printf("worker %d processed job %d: %d^2 = %d\n",
id, job.ID, job.Input, output)
results <- Result{Job: job, Output: output}
}
}
func main() {
const (
numWorkers = 3
numJobs = 10
)
jobs := make(chan Job, numJobs)
results := make(chan Result, numJobs)
var wg sync.WaitGroup
for w := 1; w <= numWorkers; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
// Dispatch jobs
for j := 1; j <= numJobs; j++ {
jobs <- Job{ID: j, Input: j}
}
close(jobs)
// Close results after all workers finish
go func() {
wg.Wait()
close(results)
}()
// Collect results
total := 0
for r := range results {
total += r.Output
}
fmt.Println("sum of squares:", total)
}