Detecting data races with -race
- Version
- 1.27
- Since
- 1.1
- Review
- Draft
Summary#
The race detector instruments a Go program to report unsynchronized accesses to the same memory when at least one is a write. Run it with go test -race or go run -race.
Syntax#
go test -race ./...
go run -race main.go
Example#
The test starts two goroutines that increment one counter under a mutex. Its script prints a stable result after the instrumented test succeeds.
(
set -eu
dir=$(mktemp -d "${TMPDIR:-/tmp}/dlr-go-a-race.XXXXXXXX")
trap 'rm -rf "$dir"' EXIT
trap 'exit 1' HUP INT TERM
cd "$dir"
export GOTOOLCHAIN=local
cat > counter_test.go <<'GO'
package counter
import (
"sync"
"testing"
)
func TestCounter(t *testing.T) {
var mu sync.Mutex
var workers sync.WaitGroup
count := 0
workers.Add(2)
for i := 0; i < 2; i++ {
go func() {
defer workers.Done()
mu.Lock()
count++
mu.Unlock()
}()
}
workers.Wait()
if count != 2 {
t.Fatalf("counter = %d, want 2", count)
}
}
GO
if ! go test -race counter_test.go > test.log 2>&1; then
cat test.log >&2
exit 1
fi
printf '%s\n' 'race check passed'
)
Expected output#
race check passed
On failure, the script prints the test diagnostic. Race reports can vary in stack locations and which access appears first.
Common mistakes#
WARNING: DATA RACE reports two goroutines that accessed the same memory without synchronization, at least one of them writing. The report shows both access stacks and where each goroutine was created. Synchronize those accesses.
A passing run covers only code paths exercised during that run. Use representative tests. A WaitGroup waits for workers to finish and does not serialize two writes within those workers. Keep the mutex around the increment, including its read of the previous value.
Version applicability#
The -race flag and test style shown are available from Go 1.1 on supported platforms. Platform support expanded in later versions. Outside macOS, enable cgo and install a compatible C compiler. Since Go 1.20, the macOS race detector can run without cgo.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0