Detect data races with go test -race
Detect data races with go test -race
The race detector instruments memory accesses and synchronization to detect conflicting unsynchronized accesses during execution. Run go test -race -count=1 -timeout=10s in a supported local environment (CGO and a compatible C compiler are needed on this Linux toolchain). A passing test with incorrect synchronization can still report a race.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "sync" "testing")
func TestLesson(t *testing.T) { var mu sync.Mutex var wg sync.WaitGroup count := 0 for i := 0; i < 4; i++ { wg.Add(1) go func() { defer wg.Done() for j := 0; j < 20; j++ { mu.Lock() count++ mu.Unlock() } }() } wg.Wait() if count != 80 { t.Fatal(count) }}Run with and without -race. Both must pass the functional assertion. The instrumented run must also report no race for the exercised paths. A race report identifies the conflicting accesses and goroutine creation stacks; inspect the shared location and missing synchronization, not just the final count.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonAtomic counter alternative
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "sync" "sync/atomic" "testing")
func TestLesson(t *testing.T) { var count atomic.Int64 var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go func() { defer wg.Done(); count.Add(2) }() } wg.Wait() if got := count.Load(); got != 6 { t.Fatal(got) }}Atomic addition is appropriate for this isolated counter. It does not make a larger transaction atomic. The intentionally racy negative fixture in the admin evidence is run separately; never mix a known failing race test into a passing learner test suite.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Use a mutex to protect a map of per-key counts; two workers each increment key a ten times. Assert 20 and run with -race. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency testing 03: Detect data races with go test -race
Check the lesson objective before moving on.
What can -race detect even when output is correct?
Why use a mutex for a shared map update?