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. This leads to undefined behavior and hard-to-detect bugs.
In Go, data races can be detected using the -race tool when running a program:
go run -race main.go
Example of a data race:
package main
import (
"fmt"
"time"
)
func main() {
var counter int
go func() {
counter = 1
}()
counter = 2
time.Sleep(time.Second)
fmt.Println(counter)
}
Here, two goroutines write to counter simultaneously without synchronization, which causes a data race. To avoid this, mutexes, channels, or other synchronization mechanisms are used.