# 致命错误：并发 map 迭代和 map 写入

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

## 根因

一个 goroutine 正在迭代 map，而另一个 goroutine 正在写入该 map，导致竞态条件。

## 版本兼容性

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

## 解决方案

1. **Use sync.RWMutex to protect both reads and writes** (95% 成功率)
   ```
   var mu sync.RWMutex
mu.RLock()
for k, v := range myMap { ... }
mu.RUnlock()
mu.Lock()
myMap[key] = value
mu.Unlock()
   ```
2. **Use sync.Map for concurrent-safe map operations** (90% 成功率)
   ```
   var m sync.Map
m.Store(key, value)
m.Load(key)
   ```

## 无效尝试

- **Using a sync.Mutex only around writes** — Iteration also needs protection; concurrent iteration and write still race. (85% 失败率)
- **Using a RWMutex for reads but not for iteration** — Iteration is a read operation but may still race with writes if not locked. (80% 失败率)
