go
runtime_error
ai_generated
true
fatal error: 并发 map 迭代与写入
fatal error: concurrent map iteration and map write
ID: go/concurrent-map-iteration-write
80%修复率
90%置信度
0证据数
2024-06-19首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.19 | active | — | — | — |
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
对 map 的 range 迭代与另一个 goroutine 对同一 map 的写入并发执行。运行时检测到迭代器与写入冲突后终止程序。
English
A range loop over a map runs concurrently with a write to the same map in another goroutine. The runtime detects the iterator/writer conflict and aborts.
解决方案
-
95% 成功率
Hold a read lock for the whole iteration and a write lock for mutations: s.mu.RLock() for k, v := range s.m { _ = k; _ = v } s.mu.RUnlock() -
90% 成功率
Snapshot keys under lock, then iterate the snapshot: s.mu.RLock() keys := make([]string, 0, len(s.m)) for k := range s.m { keys = append(keys, k) } s.mu.RUnlock() for _, k := range keys { _ = k }
无效尝试
常见但无效的做法:
-
90% 失败
Assigning a map copies only the header, not the contents; both variables share the same underlying map, so writes still race with iteration.
-
88% 失败
Sleeping widens or shifts the race window but does not synchronize; the fatal error still occurs under load.