Chapter 0 · Section 7 of 8 · 1 min read
Pitfalls
Three ways to convince yourself the bug is not there. Each one feels reasonable.
1. "I ran it and the answer was right"
A correct answer in one run says little about code with a race. In the simulator you saw 778 of 1000 seeds end correct at low switching, and none at high switching, from the same program. The Python counter in the last section gave the right total three times in a row, and its own documentation still lists the operation as not atomic.
What to do instead: run tests under go test -race, and run them more than once. A passing run with the detector on is much stronger evidence than a passing run with it off.
2. "Only one goroutine writes, the others just read"
The definition says at least one of the accesses is a write. One writer and one reader on the same variable, with nothing ordering them, is a data race. The reader can see an old value, or, for larger values, a half-updated one.
What to do instead: treat any variable touched by two goroutines, where one changes it, as needing coordination. Part 1 shows how.
3. "I added a sleep so the other goroutine finishes first"
func main() {
data := 0
go func() { data = 42 }()
time.Sleep(100 * time.Millisecond) // "long enough"
fmt.Println(data)
}Run normally, this prints 42. Run with go run -race, it reports:
WARNING: DATA RACE
Read at 0x00c000122038 by main goroutine:
main.main()
.../main.go:12 +0xb0
Previous write at 0x00c000122038 by goroutine 7:
main.main.func1()
.../main.go:10 +0x2c
Goroutine 7 (finished) created at:
main.main()(File paths shortened; I ran this on Go 1.25.2.) A sleep makes the bad ordering less likely. It does not create an ordering that the program or the Go memory model can rely on. The detector flags it because nothing connects the write to the read.
What to do instead: wait for the goroutine with something that coordinates, such as a sync.WaitGroup or a channel. Chapters 9 and 16 cover both.