Race-condition detection dynamically analyzes concurrent execution to find conflicting unsynchronized accesses to shared data. In Go, race detection is enabled with the --race flag on tools such as go run and go test. section 5.2.2 section 1.2.4
Use race detection during development to:
- Run tests with the race detector and include the check in code review or continuous integration. section 5.2.2 section 1.2.4
- Treat concurrent map writes as a synchronization problem, then protect shared state with a mutex. section 5.2.2
Concurrent word counter
A word-counting command processes multiple files in separate goroutines while updating one words.found map. Running it normally can produce “fatal error: concurrent map writes”; running go run --race reports the read and write stacks and identifies the conflicting access in tallyWords. Adding a sync.Mutex to the words structure and locking around map access prevents simultaneous modification.
