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

Get Go: Design Patterns for Real-World Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.