go
runtime_error
ai_generated
true
fatal error: 并发遍历 map 并写入
fatal error: concurrent map iteration and map write
ID: go/fatal-error-concurrent-map-iteration-and-map-write
80%修复率
90%置信度
0证据数
2024-06-18首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
一个 goroutine 正在 range 遍历 map,同时另一个 goroutine 写入该 map,运行时检测到并中止。
English
One goroutine ranges over a map while another goroutine writes to it, which the runtime detects and aborts.
解决方案
-
92% 成功率
Hold a sync.RWMutex: mu.RLock(); for k, v := range m { ... }; mu.RUnlock(), and mu.Lock() for writes. -
90% 成功率
Snapshot under lock: mu.RLock(); snapshot := make(map[K]V, len(m)); for k, v := range m { snapshot[k] = v }; mu.RUnlock(); then range over snapshot.
无效尝试
常见但无效的做法:
-
85% 失败
The copy itself races with the writer; the runtime aborts during the copy loop.
-
90% 失败
Maps have no index operator; this does not compile, and even an equivalent iteration still races.