# 警告：数据竞争（协程读操作）

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

## 根因

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

## 版本兼容性

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

## 解决方案

1. **Use sync.RWMutex for read preference** (97% 成功率)
   ```
   var mu sync.RWMutex
var data map[string]int
read := func(key string) int {
    mu.RLock()
    defer mu.RUnlock()
    return data[key]
}
write := func(key string, val int) {
    mu.Lock()
    defer mu.Unlock()
    data[key] = val
}
   ```
2. **Use channels to communicate instead of shared memory** (95% 成功率)
   ```
   ch := make(chan int)
go func() {
    v := <-ch
    // use v
}()
ch <- 42
   ```

## 无效尝试

- **Using a local copy of the variable** — The copy is made before the write, but the race still exists at the read point. (70% 失败率)
- **Adding more goroutines to distribute load** — More goroutines increase the chance of race conditions. (85% 失败率)
