我使用-race
go工具参数运行测试,输出
--- FAIL: TestRaceCondition (0.00s)
testing.go:853: race detected during execution of test
func TestRaceCondition(t *testing.T) {
var map sync.Map
for i := 0; i < 10; i++ {
go func() {
map.Store(strconv.Itoa(i), nil)
}()
}
}
我不明白,因为根据doc,
映射可以安全地由多个goroutine并发使用,而无需
附加锁定或协调。
最佳答案
比赛在i
上。通过将值传递给函数而不是引用单个局部变量来进行修复:
func TestRaceCondition(t *testing.T) {
var map sync.Map
for i := 0; i < 10; i++ {
go func(i int) {
map.Store(strconv.Itoa(i), nil)
}(i)
}
}
另一个选择是在循环内声明另一个变量
i
:func TestRaceCondition(t *testing.T) {
var map sync.Map
for i := 0; i < 10; i++ {
i := i // each goroutine sees a unique i variable.
go func() {
map.Store(strconv.Itoa(i), nil)
}()
}
}
关于dictionary - 在同步 map 中检测到数据争用情况-Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59290446/