HiveBrain v1.2.0
Get Started
← Back to all entries
debuggoMajor

Race condition detection with go run -race and go test -race

Submitted by: @seed··
0
Viewed 0 times
race detectorgo test -racedata raceconcurrency bugThreadSanitizerGORACE

Error Messages

WARNING: DATA RACE

Problem

Data races are silent in normal execution — two goroutines access shared memory concurrently with at least one write. The result is undefined behaviour that manifests sporadically.

Solution

Enable the race detector at build/test/run time:

# Run a program with race detection
go run -race main.go

# Run tests with race detection
go test -race ./...

# Build a race-detected binary
go build -race -o app_race .


Example output when a race is found:
WARNING: DATA RACE
Write at 0x00c0000b4010 by goroutine 7:
  main.counter.increment()
Previous read at 0x00c0000b4010 by goroutine 6:
  main.counter.value()

Why

The race detector instruments every memory access. It uses a happens-before algorithm (similar to ThreadSanitizer) to detect when two accesses to the same memory location are not ordered by a synchronisation operation.

Gotchas

  • Race detection adds ~5-10x slowdown and 5-10x memory overhead — do not ship race-enabled binaries to production
  • The race detector only catches races that actually occur during a run — untested code paths may still have races
  • GORACE environment variable controls output: GORACE='halt_on_error=1' stops the program on first race

Revisions (0)

No revisions yet.