Lesson 06 · 50 minutes
Check many targets at once, safely
- Start goroutines and collect their results with channels and a WaitGroup
- Find a data race with `go run -race` and fix it
- Limit the work with a pool of workers and stop it with a context timeout
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your lead gives you a list of fifty ports to check on a lab machine, and each check waits for the network. One check at a time is slow, and fifty checks at once is rude to the target and to your own machine. You need a pool of a few workers. You also need to know, before you ship it, that the shared counters of the tool are safe. You will learn the parts on three hosts, then build a pool for a different job.
Recall
What does `http.Client{Timeout: ...}` protect you from, and what does it not protect you from?
It protects you from a server that accepts the connection and never answers. It does not turn a 404 or a 500 into a Go error: those are valid responses, and you check resp.StatusCode.
What does `context.WithTimeout` return, and what must you always do with it?
It returns a context and a cancel function. Always call cancel (usually defer cancel()), so that the resources of the context are freed.
The idea
| Term | Meaning |
|---|---|
| Goroutine | A function that runs at the same time as others. Start one with go f(). It costs little, so thousands are fine. |
| Channel | A pipe between goroutines. ch <- v sends, v := <-ch receives. |
sync.WaitGroup | A counter. Add before the work, Done after it, Wait blocks until the count is 0. |
| Data race | Two goroutines touch the same variable at once, and at least one writes. The result is wrong, and not always the same. |
| Worker pool | A fixed number of goroutines that take jobs from one channel. |
- Feeder → jobCh: sends each job once, then closes jobCh
- jobCh → Worker 1: a free worker takes the next job
- jobCh → Worker 2: another worker takes the one after
- jobCh → Worker 3: a job goes to one worker only
- Worker 1 → resCh: sends its result
- Worker 2 → resCh: sends its result
- Worker 3 → resCh: sends its result
- resCh → Collector: reads until resCh is closed
Send messages when you can, and protect shared memory with a lock when you must. This lesson needs Go 1.22 or later: each pass of a for loop has its own copy of the loop variable. Older Go shared one copy, and goroutines in a loop saw the wrong value.
Worked example
1. Start goroutines and collect results
mkdir -p ~/krlab/go/conc
cd ~/krlab/go/conc
go mod init krlab/concgo mod init writes this go.mod. The lab zip holds it with go 1.22, so that it builds on every Go from 1.22:
go.mod
module krlab/conc
go 1.22Write main.go. Each goroutine sends one result into a channel with room for all of them. The finish order is not fixed, so the program sorts the results. These names are new:
| Name | Job |
|---|---|
go func() { ... }() | Starts an anonymous function as a goroutine. |
make(chan string, 3) | Makes a channel for strings with room for 3 values. |
wg.Wait() | Returns when every goroutine has called Done. |
close(ch) | Tells the reader that nothing more will come. |
sort.Strings | Sorts a slice of strings. |
main.go
package main
import (
"fmt"
"sort"
"sync"
)
func main() {
hosts := []string{"web1", "db1", "mail1"}
results := make(chan string, len(hosts))
var wg sync.WaitGroup
for _, host := range hosts {
wg.Add(1)
go func() {
defer wg.Done()
results <- "checked " + host
}()
}
wg.Wait()
close(results)
var all []string
for r := range results {
all = append(all, r)
}
sort.Strings(all)
fmt.Println(all)
}go run .[checked db1 checked mail1 checked web1]2. Cause a data race
Replace main.go. for i := 0; i < 1000; i++ is the classic counting loop: start, condition, step. A thousand goroutines add 1 to one counter. count++ is three steps (read, add, write), and two goroutines can read the same old value.
- Goroutine A → count: reads the value: 41
- Goroutine B → count: reads the value: 41 too
- Goroutine A → count: writes 42
- Goroutine B → count: writes 42: one increment is lost
main.go
package main
import (
"fmt"
"sync"
)
func main() {
count := 0
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
count++
}()
}
wg.Wait()
fmt.Println("count:", count)
}go run .
go run .count: 901
count: 925The right answer is 1000. The wrong answer changes on each run, and yours will differ.
3. Catch it with the race detector
The option -race of go run adds checks to the program. It is slower, but it names the lines. It needs a C compiler, which test 4 of labcheck (in the set-up lesson) checks.
go run -race .==================
WARNING: DATA RACE
Read at 0x00c000222028 by goroutine 11:
main.main.func1()
/home/you/krlab/go/conc/main.go:15 +0x7b
Previous write at 0x00c000222028 by goroutine 9:
main.main.func1()
/home/you/krlab/go/conc/main.go:15 +0x8d
...Line 15 is count++: one goroutine read the variable while another wrote it.
4. Fix it with a mutex
A mutex (mutual exclusion lock) is a value of type sync.Mutex. It lets one goroutine at a time into the part between Lock and Unlock. Add var mu sync.Mutex below count := 0, and change the goroutine.
go func() {
defer wg.Done()
mu.Lock()
count++
mu.Unlock()
}()go run -race .count: 1000There is no warning, and the answer is right. A second fix is to send each increment through a channel to one goroutine that owns the counter.
5. Build a bounded worker pool
A channel made with make(chan int) has no room: a send waits until another goroutine receives. Replace main.go. Three workers take jobs from jobCh. A feeder puts the numbers 1 to 10 in. A worker does the job and sends the number to resCh. Each channel has one closer:
| Channel | Closed by | Why |
|---|---|---|
jobCh | The feeder, after the last job. | The range loops of the workers end. |
resCh | A closer goroutine, after wg.Wait(). | The loop in run ends. |
The closer is a separate goroutine because run is busy reading resCh. No worker may close resCh, because the others still send. check pretends to do 100 ms of network work.
main.go
package main
import (
"fmt"
"sync"
"time"
)
func check(job int) {
time.Sleep(100 * time.Millisecond)
}
func run(jobs, workers int) int {
jobCh := make(chan int)
resCh := make(chan int)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobCh {
check(j)
resCh <- j
}
}()
}
go func() {
defer close(jobCh)
for j := 1; j <= jobs; j++ {
jobCh <- j
}
}()
go func() {
wg.Wait()
close(resCh)
}()
done := 0
for range resCh {
done++
}
return done
}
func main() {
start := time.Now()
fmt.Println("done:", run(10, 3))
fmt.Println("took:", time.Since(start).Round(100*time.Millisecond))
}go run -race .done: 10
took: 400msOne by one, ten jobs would take a second. Three workers need four rounds: 400 ms. The worker count is the limit, however many jobs you have.
6. Add a context to stop the pool
A select waits on several channels and runs the first one that is ready. time.After(d) is a channel that receives a value after d. ctx.Done() is a channel that closes when the context ends. check now waits for either one and gives up when the context ends. The feeder stops when the context ends. The result carries the error, so run counts the failures. (done, failed int) after the inputs of run names its two results. They are variables that start at 0, and return done, failed hands them back. Replace main.go.
main.go
package main
import (
"context"
"fmt"
"sync"
"time"
)
type result struct {
job int
err error
}
func check(ctx context.Context, job int) error {
select {
case <-time.After(100 * time.Millisecond):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func run(ctx context.Context, jobs, workers int) (done, failed int) {
jobCh := make(chan int)
resCh := make(chan result)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobCh {
resCh <- result{j, check(ctx, j)}
}
}()
}
go func() {
defer close(jobCh)
for j := 1; j <= jobs; j++ {
select {
case jobCh <- j:
case <-ctx.Done():
return
}
}
}()
go func() {
wg.Wait()
close(resCh)
}()
for r := range resCh {
if r.err != nil {
failed++
} else {
done++
}
}
return done, failed
}
func main() {
start := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done, failed := run(ctx, 10, 3)
fmt.Println("done:", done, "failed:", failed)
fmt.Println("took:", time.Since(start).Round(100*time.Millisecond))
}go run -race .done: 10 failed: 0
took: 400ms7. Let the timeout stop the work
Change the timeout to 250*time.Millisecond and the call to run(ctx, 50, 3).
go run -race .done: 6 failed: 3
took: 300msThe third round was still running at 250 ms, so its 3 jobs failed with context deadline exceeded.
8. The finished file
This is the whole file as it stands after the steps above, with the timeout of step 7. The lab files of the course hold it.
The finished file: main.go
main.go
package main
import (
"context"
"fmt"
"sync"
"time"
)
type result struct {
job int
err error
}
func check(ctx context.Context, job int) error {
select {
case <-time.After(100 * time.Millisecond):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func run(ctx context.Context, jobs, workers int) (done, failed int) {
jobCh := make(chan int)
resCh := make(chan result)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobCh {
resCh <- result{j, check(ctx, j)}
}
}()
}
go func() {
defer close(jobCh)
for j := 1; j <= jobs; j++ {
select {
case jobCh <- j:
case <-ctx.Done():
return
}
}
}()
go func() {
wg.Wait()
close(resCh)
}()
for r := range resCh {
if r.err != nil {
failed++
} else {
done++
}
}
return done, failed
}
func main() {
start := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
defer cancel()
done, failed := run(ctx, 50, 3)
fmt.Println("done:", done, "failed:", failed)
fmt.Println("took:", time.Since(start).Round(100*time.Millisecond))
}Your turn
Check fifty ports with a pool. There are no steps here: use what the worked example showed.
In ~/krlab/go/pool, write a program with a pool of 5 workers. The jobs are the port numbers 9000 to 9049. The function that checks a port is given as a rule: a port is open when it can be divided by 4 or by 9 with no rest (use %). A port that can be divided by 25 cannot be reached: its check returns an error, and it counts as failed and never as open, even if the first rule says open. A worker sends one result for each port, with the port, the open flag and the error. The main goroutine reads the results until the channel is closed, and prints open: with the count, sum: with the sum of the open ports and failed: with the number of errors.
Then add a second part to the same program. Start 400 goroutines. Each one adds 3 to a shared total. Print total: with its value. Run the program with go run -race . and make the race detector stay quiet. To see the problem first, run it once with no lock: the detector then prints WARNING: DATA RACE.
Check yourself
Why does `count++` from many goroutines give a different answer on each run?
It is a read, an add and a write. Two goroutines can read the same value and write back the same result, so an increment is lost. How many depends on timing.
What would happen to the pool if nobody closed `jobCh`?
The workers would wait for ever on range jobCh, wg.Wait() would never return, and the program would hang.
Why is a pool of 100 workers better than 65,000 goroutines for a port scan?
Each connection uses a file descriptor, and the system limits them. 65,000 at once can hit the limit, flood the target and give false "closed" results. A pool keeps the load steady.
Field notes
- The race detector only finds races that run. Use it in every test and on a real workload in a test environment. It costs memory and time, so keep it out of production.
- Every goroutine needs a way to end: a closed channel or a cancelled context. A goroutine that never ends is a leak, seen as memory that rises over days.
- Sending on a closed channel panics. Only the sender closes, and only once. With many senders, use a separate closer, as in step 5.
- Mind the file descriptor limit (
ulimit -n). 1000 workers on a system that allows 1024 descriptors fail in odd ways. Pick the worker count from the limit and from what the target can take, and make it a flag.