liveBook · Manning

Race flag

As explained in 100 Go Mistakes and How to Avoid Them

The Go command-line flag that enables compiler instrumentation and runtime detection of data races.

Forgetting Go’s -race flag leaves concurrent tests without runtime race detection. The flag makes the compiler instrument memory accesses, then monitors them while the program or tests run; it is not static analysis. section 11.2

$ go test -race ./...

Run the race detector across the test suite with go test -race ./.... section 11.2

A race becomes visible only when executed

A goroutine increments i while the main goroutine reads it. Running this program with -race produces a warning identifying the conflicting goroutines, source locations, and goroutine creation site.

Apply the flag according to its cost and execution context:

  • Use it routinely during local testing and continuous integration for concurrent applications. section 11.10 section 11.2
  • Expect memory usage to increase by 5–10× and execution time by 2–20×. section 11.2
  • Avoid it in production unless a canary release justifies the overhead; use the race build constraint when a test cannot run under -race. section 11.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains compiler instrumentation, command use, warning interpretation, runtime overhead, and production trade-offs.
Examples
Uses a racing increment-and-read program, its diagnostic warning, the go test command, and a race-excluding build constraint.
What it assumes
Assumes familiarity with goroutines and data races; teaches how to enable the detector and interpret its warnings.
What you can do after
Diagnose runtime data races by running instrumented tests and reading goroutine, access-location, and creation-site details.
How it connects
Connects data races with goroutines, compiler instrumentation, runtime detection, continuous integration, and build constraints.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.