在同步地图中检测到数据争用情况-Golang

我使用-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并发使用,而无需   额外的锁定或协调。

aidou309 回答:在同步地图中检测到数据争用情况-Golang

比赛在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)
        }()
    }
}
本文链接:https://www.f2er.com/2939990.html

大家都在问