在 sync.Map 中检测到数据竞争条件 - Golang
Data race condition detected in sync.Map - 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 [...] is safe for concurrent use by multiple goroutines without
additional locking or coordination.
比赛在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)
}()
}
}
我运行 使用-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 [...] is safe for concurrent use by multiple goroutines without additional locking or coordination.
比赛在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)
}()
}
}