将地图分配给另一个地图在golang中安全吗? [英] Assign a map to another map is safety in golang?
本文介绍了将地图分配给另一个地图在golang中安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类似的代码:
m := make(map[interface{}]interface{})
//read
for i := 0; i< 10000; i++ {
go func() {
for range m {
}
}()
}
//write
for i := 0; i< 10000; i++ {
go func() {
mTemp := make(map[interface{}]interface{})
m = mTemp
}()
}
有10000个读goroutine访问m,另外10000个写goroutine为m分配了一个新映射,这是安全的吗?
There are 10000 read goroutine access m,and another 10000 write goroutine assign a new map to m, and it's safety?
推荐答案
您有goroutine读取 m
变量,而goroutine则编写了 m
变量而没有显式同步.这是一场数据竞赛,因此行为不确定.
You have goroutines reading the m
varaible, and goroutines writing the m
variable without explicit synchronization. This is a data race, and therefore undefined behaviour.
在启用种族检测器的情况下运行它:
Run it with the race detector enabled:
$ go run -race play.go
==================
WARNING: DATA RACE
Write at 0x00c00008c000 by goroutine 15:
main.main.func2()
/home/icza/gows/src/play/play.go:17 +0x46
Previous read at 0x00c00008c000 by goroutine 5:
main.main.func1()
/home/icza/gows/src/play/play.go:8 +0x45
Goroutine 15 (running) created at:
main.main()
/home/icza/gows/src/play/play.go:15 +0xdd
Goroutine 5 (finished) created at:
main.main()
/home/icza/gows/src/play/play.go:7 +0xa4
==================
Found 1 data race(s)
exit status 66
查看相关问题:
Also an example which breaks Go's memory safety with intentional data race: Golang data races to break memory safety
这篇关于将地图分配给另一个地图在golang中安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文