检测数据竞争条件的方法在sync.Map中 - Golang
时间:2024-02-26
浏览: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学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
热门专题
