Data race
A data race is two goroutines accessing the same memory at the same time, without synchronization, where at least one access is a write. In Go that is a bug; the race detector exists to find it.
Detailed Explanation
n++ looks like one statement. It is a load, an add, and a store. Two goroutines can both load 0 and both store 1. You lost an increment. Worse cases tear multi-word values or let the compiler assume no concurrent writes and reorder operations. The Go memory model says a program with a data race has no guaranteed behaviour for the racing memory.
Synchronization that removes the race. A mutex around every access. A channel send that happens-before the receive that reads the value. atomic.Store / Load on that word. WaitGroup.Wait after Done before the parent reads results. Closing a channel happens-before a receive that sees the close.
What is not enough. "I don't think they overlap." "The sleep is long enough." "It is only a bool." A bool write concurrent with a read is still a race. time.Sleep is not a happens-before edge you should rely on.
Benign races are not a thing you should keep. Some people claim a counter used only for metrics can race. The detector will still flag it, and the compiler may still surprise you. Use atomic.Int64 for that counter.
What it costs. A race is a Heisenbug: it fails in production under load and passes on your laptop. -race tests and a clear ownership story (this goroutine owns the struct until it sends it) are cheaper than debugging torn state.
Code Examples
package main
import "fmt"
func race() int {
var n int
go func() { n++ }()
n++
return n // race: both increment n
}
func main() {
fmt.Println(race())
}func safe() int {
ch := make(chan int, 1)
go func() { ch <- 1 }()
return 1 + <-ch // receive synchronizes
}Common Gotchas
Concurrent map write is a fatal runtime error, not only a detector report
lock or use `sync.Map`.
A race on a pointer word can make you follow a half-updated pointer
use `atomic.Pointer` or a mutex.
Returning a slice that another goroutine still mutates is a race on the array
Returning a slice that another goroutine still mutates is a race on the array