A worker pool shares many jobs between a few goroutines.
What to build
A program where three workers calculate squares of numbers.
Requirements
- Read n, then n whole numbers (jobs).
- Start 3 worker goroutines. Each takes jobs from a channel and sends back the square of the number, as an
int64, with the job's position. - Collect all n results, and print them in the order of the jobs:
NUMBER squared is RESULT.
Input
Line 1: n. Then n whole numbers.
Output
n lines.
Constraints
1 ≤ n ≤ 100; each number is between -50000 and 50000.
Example
Input:
4
1 2 3 4
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
Why it works
Workers finish in any order, so each result carries its position. main stores it in a slice by position and prints the slice at the end, which gives the same output on every run.
Examples
Example 1 · Input
4 1 2 3 4
Expected output
1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16
Example 2 · Input
3 -7 0 12
Expected output
-7 squared is 49 0 squared is 0 12 squared is 144
Hints
Hint 1
Start 3 workers that read from a jobs channel and write result values to a results channel; close jobs after sending everything.
Hint 2
Send the job index with each job (a small struct) so main can put every result in the right place.
Solution
Show one correct solution (try it yourself first)
package main
import (
"fmt"
"sync"
)
type job struct {
index int
value int64
}
type result struct {
index int
value int64
}
func worker(jobs <-chan job, results chan<- result, wg *sync.WaitGroup) {
defer wg.Done()
for j := range jobs {
results <- result{j.index, j.value * j.value}
}
}
func main() {
var n int
fmt.Scan(&n)
nums := make([]int64, n)
for i := range nums {
fmt.Scan(&nums[i])
}
jobs := make(chan job, n)
results := make(chan result, n)
var wg sync.WaitGroup
for w := 0; w < 3; w++ {
wg.Add(1)
go worker(jobs, results, &wg)
}
for i, v := range nums {
jobs <- job{i, v}
}
close(jobs)
wg.Wait()
close(results)
squares := make([]int64, n)
for r := range results {
squares[r.index] = r.value
}
for i, v := range nums {
fmt.Printf("%d squared is %d\n", v, squares[i])
}
}