# 致命错误：并发map读写操作

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

## 根因

一个协程读取map时，另一个协程在无同步的情况下写入该map。

## 版本兼容性

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

## 解决方案

1. **Use sync.RWMutex for read-write protection** (97% 成功率)
   ```
   var mu sync.RWMutex
m := make(map[string]int)
// write
mu.Lock()
m["key"] = 1
mu.Unlock()
// read
mu.RLock()
val := m["key"]
mu.RUnlock()
   ```
2. **Use a single goroutine to own the map and communicate via channels** (95% 成功率)
   ```
   ch := make(chan request)
go func() {
    m := make(map[string]int)
    for req := range ch {
        switch req.op {
        case "read":
            req.resp <- m[req.key]
        case "write":
            m[req.key] = req.val
        }
    }
}()
   ```

## 无效尝试

- **Using a read-only copy of the map** — Copying a map during concurrent writes is also racy. (75% 失败率)
- **Using a channel to serialize access** — If not done correctly, it can introduce deadlocks. (60% 失败率)
