Detecting race conditions
Debugging concurrent code with a race condition can be time consuming and frustrating. When a race condition occurs, it is usually inconsistent and displays little to no discernible pattern. Fortunately, since Version 1.1, Go has included a race detector as part of its command-line tool chain. When building, testing, installing, or running Go source code, simply add the -race
command flag to enable the race detector instrumentation of your code.
For instance, when the source file golang.fyi/ch09/sync1.go
(a code with a race condition) is executed with the -race
flag, the compiler's output shows the offending goroutine locations that caused the race condition, as shown in the following output:
$> go run -race sync1.go
==================
WARNING: DATA RACE
Read by main goroutine:
main.main()
/github.com/vladimirvivien/learning-go/ch09/sync1.go:28 +0x8c
Previous write by goroutine 5:
main.(*Service).Start.func1...