代码:
package main
func main() {
c := make(chan bool)
m := make(map[string]string)
go func() {
m["1"] = "a" // First conflicting access.
c <- true
}()
m["2"] = "b" // Second conflicting access.
<-c
for k, v := range m {
fmt.Println(k, v)
}
}
执行 go run -race test.go
,结果为
WARNING: DATA RACE
Write at 0x00c00011c180 by goroutine 7:
runtime.mapassign_faststr()
/usr/local/Cellar/go/1.18/libexec/src/runtime/map_faststr.go:203 +0x0
main.main.func1()
/Users/admin/Downloads/test.go:9 +0x50
Previous write at 0x00c00011c180 by main goroutine:
runtime.mapassign_faststr()
/usr/local/Cellar/go/1.18/libexec/src/runtime/map_faststr.go:203 +0x0
main.main()
/Users/admin/Downloads/test.go:12 +0x127
Goroutine 7 (running) created at:
main.main()
/Users/admin/Downloads/test.go:8 +0x10a
==================
1 a
2 b
Found 1 data race(s)
exit status 66
官方文档: https://go.dev/doc/articles/race_detector
大概了解了一下 Memory Model ,还有 CPU 的乱序执行什么的,对这个例子还是不太理解,有没有大佬指点一二。
1
dongtingyue 2022-10-20 18:56:29 +08:00
出现 RACE 就说明存在多个线程同时操作数据的情况,需要加锁
|
2
wtfedc OP @dongtingyue 突然反应到,我对 map 的理解可能不太对,还以为修改不同的 key ,就可以并发写。
|