# 致命错误：并发映射写入

- **ID:** `go/fatal-error-concurrent-map-writes`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 94%

## 根因

多个 goroutine 在没有同步的情况下写入同一个映射，触发了 Go 运行时的竞态检测器。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| go1.20 | active | — | — |
| go1.21 | active | — | — |
| go1.22 | active | — | — |

## 解决方案

1. ```
   使用 sync.RWMutex 保护映射：var mu sync.RWMutex; mu.Lock(); m[key] = value; mu.Unlock()
   ```
2. ```
   使用 sync.Map 进行并发访问：var m sync.Map; m.Store(key, value); value, ok := m.Load(key)
   ```
3. ```
   重构代码，使用单个 goroutine 拥有映射并通过通道进行通信
   ```

## 无效尝试

- **Use a map with a mutex but lock only for writes, not reads** — Reads without locking can still cause data races and panic (70% 失败率)
- **Replace map with sync.Map without understanding its semantics** — sync.Map is optimized for specific patterns (append-only, write-once); misuse can be slower or incorrect (60% 失败率)
- **Ignore the error and rely on -race flag to catch it later** — The error is fatal and crashes the program immediately; cannot be ignored (95% 失败率)
