在 sync.Map 中检测到数据竞争条件 - Golang

Rob*_*bin -2 dictionary go race-condition

我使用-racego 工具参数运行测试,输出

--- FAIL: TestRaceCondition (0.00s)
    testing.go:853: race detected during execution of test
Run Code Online (Sandbox Code Playgroud)
func TestRaceCondition(t *testing.T) {
    var map sync.Map
    for i := 0; i < 10; i++ {
        go func() {
            map.Store(strconv.Itoa(i), nil)
        }()
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白,因为根据文档,

Map [...] 对于多个 goroutine 并发使用是安全的,无需额外的锁定或协调。

Cer*_*món 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是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)
        }()
    }
}
Run Code Online (Sandbox Code Playgroud)