I am confusing for following code, what's the difference between go run
with go run -race
, Does the -race
will change the program behavior?
// test.go
package main
import "fmt"
func main() {
c := make(chan string)
go func() {
for i := 0; i < 2; i++ {
c <- "hello there"
}
}()
for msg := range c {
fmt.Println(msg)
}
}
when go run test.go
, result is :
hello there
hello there
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/Users/donghui6/go/src/jd.com/iaas-sre/test/test.go:14 +0xf4
exit status 2
when go run -race test.go
, program will hang as following:
hello there
hello there
so, who can tell me what happened when use -race
flag
what happen[s] when use '-race' flag in go build
Then the program is built with the so called "race detector" enabled. Dataraces are a programming error and any program with a datarace is invalid and its behaviour is undefined. You must never write code with data races.
A data race is when two or more goroutines read and write to the same memory without proper synchronisation. Data races happen but are a major fault of the programmer.
The race detector detects unsynchronised read/writes to the same memory and reports them as a failure (which it is). Note that if the race detector detects a data race your code is buggy even if it runs "properly" without -race.
The race detector is not on always because detecting data races slows down execution drastically.