我使用-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,
Map [...]可安全地被多个goroutine并发使用,而无需 额外的锁定或协调。
答案 0 :(得分:6)
比赛在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)
}()
}
}