Race Conditions

Let’s learn how to detect and prevent race conditions.

A data race condition

A data race condition is a situation where two or more running elements, such as threads and goroutines, try to take control of or modify a shared resource or shared variable of a program. Strictly speaking, a data race occurs when two or more instructions access the same memory address, where at least one of them performs a write (change) operation. If all operations are read operations, then there is no race condition. In practice, this means that we might get different outputs if we run our program multiple times, and that is a bad thing.

Using the -race flag when running or building Go source files executes the Go race detector, which makes the compiler create a modified version of a typical executable file. This modified version can record all accesses to shared variables as well as all synchronization events that take place, including calls to sync.Mutex and sync.WaitGroup. After analyzing the relevant events, the race detector prints a report that can help us identify potential problems so that we can correct them.

The Go race detector

We can run the race detector tool with go run -race. If we test channels.go using go run -race, we are going to get the following output:

Get hands-on with 1200+ tech skills courses.