go run 我对以下代码感到困惑,与 之间有什么区别go run -race,-race会改变程序行为吗?
// 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)
}
}
Run Code Online (Sandbox Code Playgroud)
当 时go run test.go,结果是:
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
Run Code Online (Sandbox Code Playgroud)
当 时go run -race test.go,程序将挂起,如下所示:
hello there
hello there
Run Code Online (Sandbox Code Playgroud)
那么,谁能告诉我使用-raceflag时发生了什么
Vol*_*ker 13
在 go build 中使用“-race”标志时会发生什么
然后,在启用所谓的“竞争检测器”的情况下构建程序。数据争用是一种编程错误,任何具有数据争用的程序都是无效的,并且其行为是未定义的。您绝不能编写带有数据争用的代码。
数据竞争是指两个或多个 goroutine 在没有正确同步的情况下读取和写入同一内存。数据竞争确实存在,但这是程序员的主要错误。
竞争检测器检测到对同一内存的不同步读/写并将其报告为故障(事实确实如此)。请注意,如果竞争检测器检测到数据竞争,则即使代码在没有 -race 的情况下“正常”运行,也存在 错误。
竞争检测器并不总是打开,因为检测数据竞争会大大减慢执行速度。