1000 goroutines increment the same counter, yet the result is 985, 965 or 976. Go's race detector finds the spot with file and line.
Symptom
for i in 1 2 3; do go run ./demo/race; done ok = 985 ok = 965 ok = 976
Every run gives a different, wrong result.
Diagnosis
Run it with the race detector.
go run -race ./demo/race 2>&1 | grep -E 'WARNING|main.go|ok =|Found'
WARNING: DATA RACE
/Users/.../tag08-urlcheck/demo/race/main.go:13 +0x2c
/Users/.../tag08-urlcheck/demo/race/main.go:13 +0x3c
WARNING: DATA RACE
/Users/.../tag08-urlcheck/demo/race/main.go:13 +0x3c
/Users/.../tag08-urlcheck/demo/race/main.go:13 +0x3c
ok = 857
Found 2 data race(s)
Causes
ok++Non-atomic increment
ok++ is three steps. Two goroutines read the same value and one increment is lost.
wg.Go(func() { ok++ }) // Lesen, +1, Schreiben – nicht atomarFix
Make the increment indivisible: atomic.Int64 with Add and Load.
wg.Go(func() { ok.Add(1) })
}
wg.Wait()
fmt.Println("ok =", ok.Load())
go run -race ./demo/race
ok = 1000
Don't: Hide the problem with time.Sleep or fewer goroutines. The race just becomes rarer, not gone.
▶
Break it yourself and find it – free
Go hands-on, Day 8: concurrency with goroutines, a worker pool and the race detector, built into urlcheck.
Go to day 8 →
Go hands-on, Day 8: concurrency with goroutines, a worker pool and the race detector, built into urlcheck.
Go to day 8 →
FAQ
atomic or mutex?
For a single counter atomic is enough. As soon as several fields must stay consistent together, use sync.Mutex.
Should -race be part of the tests?
Yes. go test -race finds races that only show up now and then in normal runs.