Senior
What is a data race?
sobes.tech AI
Answer from AI
Data race — is a situation in multithreaded programs where two or more threads simultaneously access the same variable, and at least one of them performs a write, without proper synchronization.
In Go, a data race leads to undefined behavior because the order of operations is not guaranteed.
Example of a data race in Go:
package main
import (
"fmt"
"time"
)
func main() {
var counter int
go func() {
counter = 1
}()
go func() {
counter = 2
}()
time.Sleep(time.Second)
fmt.Println(counter)
}
Here, two goroutines write to the variable counter simultaneously without synchronization, leading to a data race.
To detect a data race in Go, you can use the -race flag during run or test:
go run -race main.go