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

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

## 根因

多个 goroutine 在没有同步的情况下访问同一个 slice，导致数据竞态。

## 版本兼容性

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

## 解决方案

1. **Use a mutex to synchronize all accesses** (95% 成功率)
   ```
   var mu sync.Mutex
mu.Lock()
slice[i] = value
mu.Unlock()
   ```
2. **Use atomic operations for simple types** (90% 成功率)
   ```
   var val atomic.Value
val.Store(mySlice)
// then load and use
   ```

## 无效尝试

- **Using a channel to pass slice elements** — If the underlying slice is still shared, races can occur on the backing array. (80% 失败率)
- **Copying the slice before writing** — Shallow copy shares the underlying array; deep copy needed. (75% 失败率)
