# fatal error: 并发 map 迭代与写入

- **ID:** `go/concurrent-map-iteration-write`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

对 map 的 range 迭代与另一个 goroutine 对同一 map 的写入并发执行。运行时检测到迭代器与写入冲突后终止程序。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.19 | active | — | — |
| 1.21 | active | — | — |
| 1.22 | active | — | — |

## 解决方案

1. **** (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()
   ```
2. **** (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 }
   ```

## 无效尝试

- **** — Assigning a map copies only the header, not the contents; both variables share the same underlying map, so writes still race with iteration. (90% 失败率)
- **** — Sleeping widens or shifts the race window but does not synchronize; the fatal error still occurs under load. (88% 失败率)
