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

我使用 go tool 参数运行测试-race,输出


--- 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)

        }()

    }

}

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

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


富国沪深
浏览 115回答 1
1回答

HUH函数

比赛正在进行中i。通过将值传递给函数而不是引用单个局部变量来修复:func TestRaceCondition(t *testing.T) {&nbsp; &nbsp; var map sync.Map&nbsp; &nbsp; for i := 0; i < 10; i++ {&nbsp; &nbsp; &nbsp; &nbsp; go func(i int) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.Store(strconv.Itoa(i), nil)&nbsp; &nbsp; &nbsp; &nbsp; }(i)&nbsp; &nbsp; }}i另一种选择是在循环内声明另一个变量:func TestRaceCondition(t *testing.T) {&nbsp; &nbsp; var map sync.Map&nbsp; &nbsp; for i := 0; i < 10; i++ {&nbsp; &nbsp; &nbsp; &nbsp; i := i&nbsp; // each goroutine sees a unique i variable.&nbsp; &nbsp; &nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.Store(strconv.Itoa(i), nil)&nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go