Learn Go with AI · Free online book
Chapter 7: A Taste of Goroutines
In short: Chapter 7 is a first taste of Go concurrency. Tests that send many requests at once reveal a data race, the race detector shows exactly where, and a mutex fixes it. Then you build a command that reads several files at the same time with goroutines.
Chapter 6 ended with a warning: your API answers many requests at once, and Tracker isn’t ready for that. Here’s how unready it is. While this book was being tested, two experiments were run against the Chapter 6 code. First, 50 requests to add an expense were sent to the API at the same moment, under Go’s race detector: it reported WARNING: DATA RACE in Tracker.Add. Then 200 curl requests were sent at once to the running server, and when they finished, expenses.json wasn’t even valid JSON anymore.
Every test from Chapter 6 still passed. Each test sent one request at a time, so none of them could see the problem.
In this last chapter, you’ll see the problem for yourself, then fix it. You’ll meet goroutines, Go’s way of doing several things at once, the race detector, which catches goroutines stepping on each other, a mutex, which makes them take turns, and channels, which let them pass results to each other. The AI stays the implementer. At the end, you’ll run one more full SURE loop on a new feature, with less help from the book, because by now you know the loop.
Mission
By the end of this chapter, you’ll have:
- Tests that send many requests at once, and a race detector report that shows why they fail
- A Tracker that’s safe to use from many goroutines, fixed by the AI and reviewed by you
- A new
importcommand that reads several files at the same time, built with a full SURE loop - An idea of what to learn next
Must know
- A goroutine is a function running at the same time as the rest of your program. You start one with
go:go doSomething(). Go’s HTTP server starts one for every request, which is why your API already handles requests at the same time. sync.WaitGroupwaits for goroutines to finish.wg.Go(func() { ... })starts a goroutine and keeps count;wg.Wait()waits until all of them are done. (wg.Goarrived in Go 1.25.)- A data race is two goroutines touching the same data at once, when at least one of them changes it. The result is unpredictable: lost updates, wrong totals, broken files.
go test -racefinds races, but only the ones that actually happen while your tests run. - A
sync.Mutexmakes goroutines take turns.mu.Lock()waits until no one else holds the lock;mu.Unlock()lets the next one in.defer mu.Unlock()runs the unlock when the function returns, however it returns. A mutex’s zero value is ready to use, and you must never copy one. - A channel passes values between goroutines.
ch := make(chan int)makes one;ch <- 5sends;n := <-chreceives. A send waits until someone receives, so channels also make goroutines wait for each other.
Before you start: the race detector needs a C compiler
go test -race uses a part of Go that’s built with C, so on some systems it needs a C compiler:
- macOS: nothing extra. The race detector works without Xcode.
- Linux: install GCC if you don’t have it, for example
sudo apt install gccon Ubuntu or Debian. - Windows on a 64-bit Intel or AMD processor: you need a MinGW-w64 GCC. Appendix A shows how to install one.
If something’s missing, go test -race tells you:
go: -race requires cgo; enable cgo by setting CGO_ENABLED=1
That message appears whenever Go can’t find a C compiler, on Linux too. Don’t just set CGO_ENABLED=1 as it suggests: without a compiler, you’ll only get a new error, cgo: C compiler "gcc" not found. Install the compiler, open a new terminal and try again. On Windows on an Arm processor, -race isn’t available at all; read this chapter’s race reports, and run the rest without -race.
Specify: see the race
A test that sends many requests at once
If you did the Chapter 6 practice, make its tests pass first (have the AI implement it), or remove them. Your line numbers will then differ from the book’s.
Add this test at the end of api/api_test.go, and add "sync" to its imports, between "strings" and "testing":
func TestConcurrentAdds(t *testing.T) {
h := newTestHandler(t, &ledger.MemoryStorage{})
var wg sync.WaitGroup
for range 50 {
wg.Go(func() {
rec := send(h, "POST", "/expenses", `{"category":"Food","cents":100}`)
if rec.Code != http.StatusCreated {
t.Errorf("status = %d, want %d", rec.Code, http.StatusCreated)
}
})
}
wg.Wait()
rec := send(h, "GET", "/totals", "")
want := `{"Food":5000}` + "\n"
if got := rec.Body.String(); got != want {
t.Errorf("body = %q, want %q", got, want)
}
}
for range 50 repeats 50 times. Each time, wg.Go starts a goroutine that adds one expense of 1.00. wg.Wait() waits for all 50, and then the Food total must be 50 × 100 = 5000 cents.
Inside the goroutines, the test uses t.Errorf, never t.Fatalf. t.Fatalf stops the test, and it may only be called from the test’s own goroutine.
Run it a few times, without the race detector:
go test -count=1 ./api
-count=1 tells Go to really run the tests instead of reusing a cached result. Sometimes it passes:
ok tracker/api 0.005s
And sometimes it doesn’t:
--- FAIL: TestConcurrentAdds (0.00s)
api_test.go:128: body = "{\"Food\":4900}\n", want "{\"Food\":5000}\n"
FAIL
FAIL tracker/api 0.004s
FAIL
Your total, and how often it fails, will differ. On a computer with one CPU core, it may pass every time, which is exactly why you need the race detector. One expense, or several, just vanished. Two goroutines read the same slice at the same moment, each appended its own expense, and the second write threw away the first. That’s a lost update, and it’s what makes races so nasty: the bug comes and goes.
Let the race detector look
Now run the same test with -race:
go test -race -count=1 ./api
The output is long. Here’s the start of it. Everything in <angle brackets> will be different for you: memory addresses, goroutine numbers, +0x… offsets, and the folders where your project and Go are installed. A goroutine may also be marked (finished) instead of (running). Your first report may also point at a different line, such as the Save call, or list the read and write the other way round. Read whichever comes first the same way.
==================
WARNING: DATA RACE
Read at 0x<address> by goroutine <A>:
tracker/ledger.(*Tracker).Add()
<your tracker folder>/ledger/ledger.go:38 +0x<offset>
tracker/api.NewHandler.func1()
<your tracker folder>/api/api.go:21 +0x<offset>
...
tracker/api.TestConcurrentAdds.func1()
<your tracker folder>/api/api_test.go:117 +0x<offset>
Previous write at 0x<address> by goroutine <B>:
tracker/ledger.(*Tracker).Add()
<your tracker folder>/ledger/ledger.go:38 +0x<offset>
tracker/api.NewHandler.func1()
<your tracker folder>/api/api.go:21 +0x<offset>
...
tracker/api.TestConcurrentAdds.func1()
<your tracker folder>/api/api_test.go:117 +0x<offset>
Goroutine <A> (running) created at:
sync.(*WaitGroup).Go()
<Go folder>/src/sync/waitgroup.go:<line> +0x<offset>
testing.tRunner()
<Go folder>/src/testing/testing.go:<line> +0x<offset>
testing.(*T).Run.gowrap1()
<Go folder>/src/testing/testing.go:<line> +0x<offset>
...
==================
The ... lines stand for more lines from Go’s own net/http code, your send helper and the rest of the report. After this come more WARNING: DATA RACE blocks, including one in MemoryStorage.Save, and the report ends like this:
--- FAIL: TestConcurrentAdds (0.00s)
testing.go:<line>: race detected during execution of test
FAIL
FAIL tracker/api 0.0<xx>s
FAIL
You may also see the body = ... line from before; whether the total comes out wrong changes from run to run.
How to read a race report:
WARNING: DATA RACEstarts each report.Read at ... by goroutine <A>andPrevious write at ... by goroutine <B>are the two goroutines that collided. Under each is the chain of function calls that got it there, newest first.- The first line from your code is the one to read. Here it’s
ledger.go:38, theappendinTracker.Add, in both goroutines. created atshows how each goroutine started:sync.(*WaitGroup).Gois your test’swg.Go. Your own line is at the bottom of each stack above it:api_test.go:117, thesendinside the goroutine. (Some Go versions also list your test, at line 116, undercreated at.)
The race detector doesn’t guess. It saw two goroutines really touch the same memory without taking turns.
Say where the fix belongs
The race is inside Tracker, so the fix belongs there too, not in the API. That way, every user of Tracker is safe, not just the API. Add a test to ledger/ledger_test.go that uses a Tracker from many goroutines directly, and add "sync" to that file’s imports:
func TestTrackerConcurrentUse(t *testing.T) {
tr, err := Open(&MemoryStorage{})
if err != nil {
t.Fatalf("Open() error = %v", err)
}
var wg sync.WaitGroup
for range 50 {
wg.Go(func() {
if err := tr.Add("Food", 100); err != nil {
t.Errorf("Add() error = %v", err)
}
tr.Totals()
if err := tr.Save(); err != nil {
t.Errorf("Save() error = %v", err)
}
})
}
wg.Wait()
if got := tr.Totals()["Food"]; got != 5000 {
t.Errorf("Food total = %d, want 5000", got)
}
}
Each goroutine adds, reads totals and saves, so all three of Tracker’s methods run at the same time as each other. Add a sentence to SPEC.md. The book numbers from 17 because the Chapter 6 practice used 15 and 16; use your next number.
17. Tracker is safe to use from many goroutines at once:
go test -race ./... reports no races.
Then commit your failing tests before asking the AI:
git add .
git commit -m "Add concurrency tests" -m "Learned: a test that passes can still hide a data race; go test -race finds it."
Use the AI: implementer
Make ledger.Tracker safe to use from many goroutines at once, so
that go test -race ./... passes. Put a sync.Mutex in Tracker.
Use only the standard library. Don't change any test files.
The prompt says where the lock goes. Without that, the AI might put it in the API instead. That would fix the API’s test but leave TestTrackerConcurrentUse failing, and any other code that shares a Tracker unprotected.
Review the AI’s work
Same four steps as Chapter 6.
1. Scope. git status --short should show only M ledger/ledger.go.
2. Checks. Run go run ./check, then the race detector on everything:
go test -race ./...
ok tracker 1.014s
ok tracker/api 1.016s
? tracker/check [no test files]
ok tracker/ledger 1.017s
ok tracker/money 1.012s
No WARNING. Each package takes about a second longer with -race: the race detector waits a moment before a test program exits, and on bigger programs it also makes the code itself 2 to 20 times slower, because it watches every memory access. That’s why go run ./check doesn’t use it: it would slow every check, and -race doesn’t work on every system. Run it yourself whenever you touch code that goroutines share.
3. The diff. git diff shows what changed. Here’s the book’s version:
diff --git a/ledger/ledger.go b/ledger/ledger.go
index 51eb176..e296e0a 100644
--- a/ledger/ledger.go
+++ b/ledger/ledger.go
@@ -4,6 +4,7 @@ package ledger
import (
"errors"
"fmt"
+ "sync"
)
// Expense is one thing you spent money on.
@@ -16,7 +17,9 @@ type Expense struct {
var ErrInvalidAmount = errors.New("amount must be more than zero")
// Tracker holds all your expenses and the storage they live in.
+// It is safe to use from many goroutines at once.
type Tracker struct {
+ mu sync.Mutex // guards expenses and calls to store
store Storage
expenses []Expense
}
@@ -35,12 +38,16 @@ func (tr *Tracker) Add(category string, cents int) error {
if cents <= 0 {
return fmt.Errorf("add %q: %w", category, ErrInvalidAmount)
}
+ tr.mu.Lock()
+ defer tr.mu.Unlock()
tr.expenses = append(tr.expenses, Expense{Category: category, Cents: cents})
return nil
}
// Totals returns the total in cents for each category.
func (tr *Tracker) Totals() map[string]int {
+ tr.mu.Lock()
+ defer tr.mu.Unlock()
totals := make(map[string]int)
for _, e := range tr.expenses {
totals[e.Category] += e.Cents
@@ -50,5 +57,7 @@ func (tr *Tracker) Totals() map[string]int {
// Save writes all expenses to the Tracker's storage.
func (tr *Tracker) Save() error {
+ tr.mu.Lock()
+ defer tr.mu.Unlock()
return tr.store.Save(tr.expenses)
}
4. Questions for this kind of change:
- Is every access locked?
Addwritesexpenses, whileTotalsandSaveread it. All three must lock, not only the one that writes. Break 1 below shows why. - Does
Savehold the lock while writing the file? Yes, and that’s on purpose: it also stops two saves from writingexpenses.jsonat the same time. That’s what turned the file into broken JSON in the opening experiment. - Why is the amount check before the lock? It doesn’t touch shared data, so there’s no need to make other goroutines wait for it. Keep locked sections short.
- Is
Openstill right? It builds a newTrackerwithmuleft at its zero value, which is an unlocked mutex, ready to use. Must know #4 in action.
When you can answer all four, commit:
git add .
git commit -m "Make Tracker safe for concurrent use" -m "Learned: every read and write of shared data needs the lock, not just the writes."
Review
Break it on purpose
Break 1: lock only the writes. In Totals, delete the two lines tr.mu.Lock() and defer tr.mu.Unlock(). It’s tempting, since Totals only reads. Run go test -race -count=1 ./ledger:
==================
WARNING: DATA RACE
Write at 0x<address> by goroutine <A>:
tracker/ledger.(*Tracker).Add()
<your tracker folder>/ledger/ledger.go:43 +0x<offset>
tracker/ledger.TestTrackerConcurrentUse.func1()
<your tracker folder>/ledger/ledger_test.go:81 +0x<offset>
...
Previous read at 0x<address> by goroutine <B>:
tracker/ledger.(*Tracker).Totals()
...
==================
As before, the two goroutines may be listed the other way round. It ends with race detected during execution of test and FAIL. A read during a write is still a race: Totals could see the slice halfway through changing. Put the two lines back.
Break 2: copy the mutex. Change func (tr *Tracker) Totals() to func (tr Tracker) Totals(), removing the *. It still compiles, but run go vet ./...:
ledger/ledger.go:48:10: Totals passes lock by value: tracker/ledger.Tracker contains sync.Mutex
A value receiver copies the whole Tracker, mutex included, so Totals would lock its own private copy and protect nothing. It can be worse: if it copies the Tracker while another goroutine holds the lock, the copy stays locked forever, and go test hangs. If that happens, press Ctrl+C. go vet knows this rule, and go run ./check runs go vet. Put the * back.
One more SURE loop: import
Time for a full SURE loop on a new feature, with the book stepping back. Say you’ve kept expenses on two devices, and each saved its own JSON file. You want to bring them all into Tracker.
Specify
Add to SPEC.md:
18. `go run . import FILE...` reads expenses from one or more
JSON files (same format as expenses.json), adds them all,
saves, and prints: Imported N expenses
19. The files are read at the same time, each in its own goroutine.
20. If any file can't be read, nothing is imported, and the error
names the file.
Then the tests, in ledger/storage_test.go. Add "maps" and "strings" to its imports, then add:
func TestReadAll(t *testing.T) {
dir := t.TempDir()
phone := FileStorage{Path: filepath.Join(dir, "phone.json")}
laptop := FileStorage{Path: filepath.Join(dir, "laptop.json")}
if err := phone.Save([]Expense{{Category: "Food", Cents: 350}}); err != nil {
t.Fatal(err)
}
if err := laptop.Save([]Expense{
{Category: "Fun", Cents: 1500},
{Category: "Food", Cents: 99},
}); err != nil {
t.Fatal(err)
}
got, err := ReadAll([]string{phone.Path, laptop.Path})
if err != nil {
t.Fatalf("ReadAll() error = %v", err)
}
totals := make(map[string]int)
for _, e := range got {
totals[e.Category] += e.Cents
}
want := map[string]int{"Food": 449, "Fun": 1500}
if len(got) != 3 || !maps.Equal(totals, want) {
t.Errorf("ReadAll() = %v, want 3 expenses with totals %v", got, want)
}
}
func TestReadAllMissingFile(t *testing.T) {
dir := t.TempDir()
phone := FileStorage{Path: filepath.Join(dir, "phone.json")}
if err := phone.Save([]Expense{{Category: "Food", Cents: 350}}); err != nil {
t.Fatal(err)
}
missing := filepath.Join(dir, "missing.json")
_, err := ReadAll([]string{phone.Path, missing})
if err == nil {
t.Fatal("ReadAll() error = nil, want an error for a missing file")
}
if !strings.Contains(err.Error(), "missing.json") {
t.Errorf("error %q should name the missing file", err)
}
}
Two choices in these tests are worth noticing. TestReadAll checks the totals, not the order of the expenses, because files read at the same time can finish in any order. And TestReadAllMissingFile insists that a missing file is an error, unlike FileStorage.Load, where a missing file just means “no expenses yet.” For an import, a missing file means you typed the name wrong.
Run go test ./... and you’ll see undefined: ReadAll twice. Commit:
git add .
git commit -m "Add import tests" -m "Learned: when work runs at the same time, test the result, not the order."
Use the AI
Write this prompt yourself. It should name the function (ReadAll(paths []string) ([]Expense, error) in package ledger), say that each file is read in its own goroutine with results collected over a channel, ask for an import command in main.go that matches sentence 18, and repeat your rules: standard library only, don’t change test files.
Review
Do the four steps without the book’s help: scope with git status, checks with go run ./check and go test -race ./..., every line of the diff, and the questions below. Then compare with one version that passes:
// ReadAll reads expenses from several JSON files at the same time.
// Every file must exist. If any file can't be read, ReadAll
// returns an error and no expenses.
func ReadAll(paths []string) ([]Expense, error) {
type result struct {
expenses []Expense
err error
}
results := make(chan result)
for _, path := range paths {
go func() {
expenses, err := readFile(path)
results <- result{expenses: expenses, err: err}
}()
}
var all []Expense
var firstErr error
for range paths {
r := <-results
if r.err != nil && firstErr == nil {
firstErr = r.err
}
all = append(all, r.expenses...)
}
if firstErr != nil {
return nil, firstErr
}
return all, nil
}
// readFile reads one JSON file of expenses. Unlike FileStorage.Load,
// a missing file is an error.
func readFile(path string) ([]Expense, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("import: %w", err)
}
var expenses []Expense
if err := json.Unmarshal(data, &expenses); err != nil {
return nil, fmt.Errorf("import %s: %w", path, err)
}
return expenses, nil
}
And the new part of run in main.go, placed before the add command:
if len(args) >= 2 && args[0] == "import" {
expenses, err := ledger.ReadAll(args[1:])
if err != nil {
return err
}
for _, e := range expenses {
if err := tracker.Add(e.Category, e.Cents); err != nil {
return err
}
}
if err := tracker.Save(); err != nil {
return err
}
fmt.Printf("Imported %d expenses\n", len(expenses))
return nil
}
The book’s version also updates the usage error at the end of run to usage: go run . [add CATEGORY CENTS | serve | import FILE...], so go run . import with no files says how to use it.
Questions to ask about any version, the AI’s or the book’s:
- How many goroutines start, and does every one of them finish? Here, one per file, and each sends exactly one result. The receiving loop runs once per file, even after an error. If it returned at the first error, the remaining goroutines would wait forever to send. That’s the goroutine leak from the box.
- Does it reuse
FileStorage.Load? An AI might, because it looks like the obvious choice. ButLoadtreats a missing file as “no expenses,” and yourTestReadAllMissingFilewould catch that. - What happens to a bad expense?
runpasses each one throughtracker.Add, which rejects zero and negative amounts. If one fails,runreturns beforeSave, so nothing is saved, the same all-or-nothing rule as sentence 20.
Try it
Make a file in your practice folder, phone.json, with two made-up expenses:
[
{"category": "Food", "cents": 250},
{"category": "Transport", "cents": 300}
]
From the tracker folder:
go run . import ../practice/phone.json
Imported 2 expenses
Then run go run .. If your data is where Chapter 6 left it, including the 2.50 you added with curl, you’ll see:
Welcome to Tracker. Let's see where your money goes.
Food: 9.49
Fun: 15.00
Transport: 15.00
And a file that doesn’t exist:
go run . import ../practice/phone.json ../practice/laptop.json
Error: import: open ../practice/laptop.json: no such file or directory
exit status 1
The wording after open ...: differs on Windows. Nothing was imported, not even phone.json’s expenses: run go run . and the totals haven’t changed.
Explain
Say it in your own words: how does ReadAll know when every file is done? Let the AI quiz you on channels. Then commit, with your own Learned: line.
Practice (optional)
Here’s code an AI wrote to add up spending from many goroutines. It has a mutex, and its test passes every time. It also has a data race. In your practice folder, make a small module of its own:
mkdir racy
cd racy
go mod init racy
Create spending.go:
// Package racy adds up spending from many goroutines.
package racy
import "sync"
// Spending adds up amounts in cents.
type Spending struct {
mu sync.Mutex
total int
}
// Add adds cents to the total.
func (s *Spending) Add(cents int) {
s.mu.Lock()
s.total += cents
s.mu.Unlock()
}
// Total returns the total so far.
func (s *Spending) Total() int {
return s.total
}
And spending_test.go:
package racy
import (
"sync"
"testing"
)
func TestSpending(t *testing.T) {
var s Spending
var wg sync.WaitGroup
for range 100 {
wg.Go(func() {
s.Add(100)
if s.Total() < 100 {
t.Errorf("Total() = %d, want at least 100", s.Total())
}
})
}
wg.Wait()
if got := s.Total(); got != 10000 {
t.Errorf("Total() = %d, want 10000", got)
}
}
Run go test -count=1 ./... a few times: ok every time. Now run go test -race ./.... Read the report: which two functions collide, and which line in each? Fix it, run go test -race ./... until you see ok, and then ask the AI to review your fix.
Tried it? Compare with the worked answer for Chapter 7.
What you’ve done, and what’s next
In this chapter, you saw a bug that only appears when things happen at the same time, found it with the race detector, and had the AI fix it with a mutex. Then you ran a whole SURE loop with the book stepping back, and used goroutines and a channel to read files at the same time.
Look back at the whole book. You started with a program that printed one line, and you finished with a tested, concurrent web API, organized into packages, saving to a file, with one command that checks it all. Along the way, the AI went from tutor to pair to implementer. One thing never changed: you decided what “done” meant, and you were sure you could explain every line you kept. That’s the SURE loop, and it works the same in any language and with any AI.
What to learn next
You’ve had a taste of Go. Here are good next steps, in roughly this order:
context, the standard way to cancel work and set deadlines, for example to stop handling a request when the client hangs up.- Databases, with
database/sql. A JSON file is fine for one person; a database is what lets many people share data safely. - Getting to production: configuration, logging with
log/slog, building and deploying a server, and keeping it running. - Bigger project structure: how a team keeps a Go codebase consistent as it grows.
The companion book to this one, Bogie: How to Go from Zero to Production: Conventions for AI-Assisted Go, picks up many of these. It gives you “conventions a whole team can share, and a generator that follows them”: Bogie, a Rails-style code generator for Go web apps. Bogie isn’t a framework; the code it generates is ordinary Go, and it belongs to you. Through the book, you build Bogie Depot, a complete online shop: a JSON API with small HTML pages in front of it, with real transactions, tests from the outside in, and a deployment to your own server. The habits from this book carry straight over: specify with tests, let the AI implement, and review every diff. See bogie-go.com/book.html.
Whatever you build next, the AI will keep saying “Sure!” Now you know what to ask back.