我对下面的代码感到困惑,与,会改变程序行为有什么区别吗?go run go run -race-race// test.gopackage mainimport "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) }}当 时,结果为:go run test.gohello therehello therefatal error: all goroutines are asleep - deadlock!goroutine 1 [chan receive]:main.main() /Users/donghui6/go/src/jd.com/iaas-sre/test/test.go:14 +0xf4exit status 2当 时,程序将挂起,如下所示:go run -race test.gohello therehello there所以,谁能告诉我使用标志时发生了什么-race
1 回答
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
在 Go Build 中使用 '-race' 标志时会发生什么
然后,在启用所谓的“比赛检测器”的情况下构建程序。数据竞赛是一种编程错误,任何具有数据竞赛的程序都是无效的,其行为是未定义的。切勿使用数据竞跑编写代码。
数据竞赛是指两个或多个 goroutine 在没有正确同步的情况下读取和写入同一内存。数据竞赛时有发生,但这是程序员的一个主要错误。
竞速检测器检测到对同一存储器的未同步读/写,并将其报告为故障(确实如此)。请注意,如果 race 检测器检测到数据竞跑,即使它在没有 -race 的情况下“正常”运行,您的代码也是错误的。
竞态检测器并不总是打开,因为检测数据竞跑会大大减慢执行速度。
- 1 回答
- 0 关注
- 155 浏览
添加回答
举报
0/150
提交
取消
