Hi i'm new in go and i currently still learning on it, there is a question about the difference between data race and race condition, i get a bit confused about the difference between it and can someone tell me what is the real different between those condition and the sample answer ? Thanks in advance
CodePudding user response:
A data race is a kind of race condition.
A data race is where a variable is written concurrently with other reads and writes of the variable. Here's a data race example:
x := 1
go func() { x = 2 }() // The write to x on this line executes ...
fmt.Println(x) // concurrently with the read on this line
The program can print 1, 2, or fail in some unspecified way.
A race condition is where concurrently executing code produces different results due to nondeterministic timing. Here's a race condition example (that is not a data race):
ch := make(chan int, 1)
go func() { ch <- 1 }()
go func() { ch <- 2 }()
fmt.Println(<-ch)
The goroutines race to send a value to the channel. The program can print 1 or 2.
CodePudding user response:
some reference and example can be read in https://medium.com/trendyol-tech/race-conditions-in-golang-511314c0b85