登录
首页 >  Golang >  Go问答

检测数据竞争条件的方法在sync.Map中 - Golang

来源:stackoverflow

时间:2024-02-26 12:09:24 182浏览 收藏

golang学习网今天将给大家带来《检测数据竞争条件的方法在sync.Map中 - Golang》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习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)
        }()
    }
}

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

map [...] 对于多个 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)
        }()
    }
}

理论要掌握,实操不能落!以上关于《检测数据竞争条件的方法在sync.Map中 - Golang》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>