go
runtime_error
ai_generated
true
fatal error: 并发 map 迭代与 map 写入
fatal error: concurrent map iteration and map write
ID: go/concurrent-map-write-during-range
80%修复率
90%置信度
0证据数
2024-02-27首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
一个 goroutine 正在 range 遍历 map,同时另一个 goroutine 写入同一个 map,违反了 Go 的 map 安全规则。
English
A map is being range-iterated in one goroutine while another goroutine writes to the same map, violating Go's map safety rules.
解决方案
-
97% 成功率
var mu sync.RWMutex mu.RLock() for k, v := range m { _ = k; _ = v } mu.RUnlock() // writer: mu.Lock() m[k] = v mu.Unlock() -
90% 成功率
var m sync.Map m.Range(func(k, v any) bool { return true }) m.Store(key, val)
无效尝试
常见但无效的做法:
-
90% 失败
Timing-based avoidance is unreliable; the runtime can still detect concurrent access under load.
-
95% 失败
This is a fatal runtime error, not a panic; recover cannot catch it and the process exits.