# 致命错误：并发 map 读取和 map 写入

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

## 根因

一个协程从 map 中读取，而另一个协程在没有同步的情况下写入 map，导致数据竞争。

## 版本兼容性

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

## 解决方案

1. **Use sync.RWMutex to protect both reads and writes** (95% 成功率)
   ```
   var mu sync.RWMutex
mu.RLock()
val := myMap[key]
mu.RUnlock()
   ```
2. **Use sync.Map for concurrent read/write** (90% 成功率)
   ```
   var m sync.Map
m.Load(key) // safe concurrent read
   ```

## 无效尝试

- **Use a read-write lock (sync.RWMutex) only for writes** — If reads are not protected, they can still race with writes. (60% 失败率)
- **Use a copy of the map for reads** — Copying a map while it is being written is unsafe and can cause a race. (90% 失败率)
