Data races
A race is simultaneous access to memory where at least one access writes. You look for it with the race detector, not with luck on a stand.
A data race: two goroutines touch one variable, at least one writes, and there is no synchronization between them. The result is not "sometimes a little inaccurate". The language promises nothing: a counter can lose steps, a pointer can tear, the program can crash. The message concurrent map writes is a special case. The map itself checks part of the violations. An ordinary int checks nothing.
The detector is turned on by a test:
go test -race ./...
It slows execution and eats memory, so it is run in CI, not as the only production mode. The detector finds a race only if the suspicious code actually ran. A test that never reached two goroutines proves nothing. A green -race on an empty test does not mean the service is clean.
Reading and writing different fields of one struct is also a conflict if they sit side by side without synchronization and happen at the same time. "We write different fields" does not save you if there is no agreement about the owner. It is simpler to appoint an owner: one goroutine writes the struct, the others receive copies or messages.
A closure that increments an outer counter from several goroutines is a race, even if the counter is "just an int". A channel that sends a finished value to one owner goroutine is not a race. A mutex around every access to the counter also removes the race. An atomic Add removes it for one number.
Do not cure a race with a sleep time.Sleep. A test that "usually makes it" flickers. Either the synchronization is real, or there is no test.
Practice
What is a race
Two goroutines execute
n++on one variablenwith no mutex and no channels. Is this a race?- No, int is safe as it is
- Yes
- Only if n is greater than 1000
- Only on Windows
How to catch them
Which command turns on the race detector in tests?
- go test -race ./...
- go vet -mutex ./...
- go fmt -race .
- go run -debug
Does sleep cure a race
Before reading the result, a test does
time.Sleep(time.Millisecond)so the goroutine "has time". Does that remove the data race? Writeyesorno.