Starting one goroutine per item is fine for ten items and unwise for a million: each goroutine needs memory, and whatever they all call, a database or a remote service, may not cope with a million callers at once. A worker pool bounds the concurrency. A fixed number of workers each take the next job from a shared channel until there are no jobs left. The project parses its commands this way, with four workers, and parsing stands in for any work that is slow and independent per item.
A pool raises the question of order. Workers finish in whatever order the scheduler produces, so if results are reported as they finish, the report changes from run to run. The project's output must be deterministic, so the jobs carry their index, and each worker writes its result to that index.
Predict and run
Three workers process seven items. In what order do the results appear?
package main
import (
"fmt"
"strings"
"sync"
)
func main() {
items := []string{"tent", "drill", "lamp", "hat", "stove", "rope", "map"}
results := make([]string, len(items))
jobs := make(chan int)
var wg sync.WaitGroup
for range 3 {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
results[i] = strings.ToUpper(items[i])
}
}()
}
for i := range items {
jobs <- i
}
close(jobs)
wg.Wait()
fmt.Println(results)
}Check your prediction
[TENT DRILL LAMP HAT STOVE ROPE MAP]Which worker handled which item is unpredictable, but it does not matter: results are placed by index, so the output always follows the input. Three things make the pool correct. Each worker ranges over jobs and exits when it is closed. main closes jobs after sending the last index. And wg.Wait() runs before anyone reads results. Remove close(jobs) and the program deadlocks, because the workers wait for more jobs forever.
Make it generic
The pool does not care what the items or results are, which makes it a natural generic function: Day 1 and Day 5 together. mapConcurrent below is the project's version without cancellation, which you will add in the next lesson. It never starts more workers than there are items, and always at least one, so an empty input or a zero worker count still works.
package main
import (
"fmt"
"strconv"
"sync"
)
func mapConcurrent[T, R any](items []T, workers int, f func(T) R) []R {
workers = max(1, min(workers, len(items)))
results := make([]R, len(items))
jobs := make(chan int)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
results[i] = f(items[i])
}
}()
}
for i := range items {
jobs <- i
}
close(jobs)
wg.Wait()
return results
}
type parsed struct {
n int
err error
}
func main() {
texts := []string{"5", "x", "12"}
for _, p := range mapConcurrent(texts, 4, func(s string) parsed {
n, err := strconv.Atoi(s)
return parsed{n, err}
}) {
fmt.Println(p.n, p.err)
}
fmt.Println(len(mapConcurrent([]int{}, 0, func(n int) int { return n })))
}5 <nil>
0 strconv.Atoi: parsing "x": invalid syntax
12 <nil>
0The parse failure did not stop the pool. It became part of the result, so the caller can report it at the right position. The project does the same: each parsed command carries its own error, and the loop that applies the commands prints each rejection in its input line's place.
Parallel parsing, sequential state
Notice what the project does not do concurrently. The workers only parse text, which needs no shared state. Applying commands to the ledger happens afterwards, one at a time, in input order, because the result of an order depends on every command before it. Concurrency is safe and simple when the concurrent part shares nothing, and the order-dependent part stays sequential.
Size the pool for the work
For work that mostly computes, more workers than processor cores does not help: runtime.NumCPU() is a reasonable count. For work that mostly waits, such as network calls, the right count depends on what the other side can handle. Either way, make the count a parameter, as mapConcurrent does, rather than a constant buried inside.
Practice
Your turn
Use mapConcurrent from the starter to compute the length in bytes of each of tent, 短編, lamp and hat with two workers. Then use it again to turn the numbers 1 to 5 into strings with a # in front. Print both results.
The output should be:
[4 6 4 3]
[#1 #2 #3 #4 #5]package main
import (
"sync"
)
func mapConcurrent[T, R any](items []T, workers int, f func(T) R) []R {
workers = max(1, min(workers, len(items)))
results := make([]R, len(items))
jobs := make(chan int)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
results[i] = f(items[i])
}
}()
}
for i := range items {
jobs <- i
}
close(jobs)
wg.Wait()
return results
}
func main() {
// Call mapConcurrent twice with different types.
}Hint 1: the idea
The pool is finished. Your work is in the functions you pass to it, and the type parameters follow from them.
Hint 2: a first step
For the first call, pass func(s string) int { return len(s) }. For the second, use strconv.Itoa inside a function literal.
Worked solution
package main
import (
"fmt"
"strconv"
"sync"
)
func mapConcurrent[T, R any](items []T, workers int, f func(T) R) []R {
workers = max(1, min(workers, len(items)))
results := make([]R, len(items))
jobs := make(chan int)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
results[i] = f(items[i])
}
}()
}
for i := range items {
jobs <- i
}
close(jobs)
wg.Wait()
return results
}
func main() {
names := []string{"tent", "短編", "lamp", "hat"}
fmt.Println(mapConcurrent(names, 2, func(s string) int { return len(s) }))
labels := mapConcurrent([]int{1, 2, 3, 4, 5}, 2, func(n int) string { return "#" + strconv.Itoa(n) })
fmt.Println(labels)
}[4 6 4 3]
[#1 #2 #3 #4 #5]短編 is two characters but six bytes, as on Day 3. In the first call R is int, and in the second it is string. Both results follow the input order although two workers shared the jobs.
Completion is saved in this browser only. It does not measure mastery.