Search⌘ K

Data Races and Race Conditions

Explore the concepts of data races and race conditions in Go concurrent programming. Understand how simultaneous access to shared variables can cause unexpected behavior and learn about Go's data race detector and synchronization methods to write safer concurrent code.

One of the reasons why concurrency is hard to achieve is because of data races.

Data Race

A data race happens when processes have to access the same variable concur­rently i.e. one process reads from a memory location while another simultaneously writes to the exact same memory location.

The following function is an example of a data race:

Go (1.6.2)
package main
import "fmt"
func main() {
number := 0;
go func(){
number++ //reading and modifying the value of 'number'
}()
fmt.Println(number) //reading the value of 'number'
}

We increment the value of the variable number i.e. we first access the value, add 1 to it and then write the new value back to the memory. number++ takes place using an anonymous go routine. In the next step, we read the value of number and print it ...