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

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

## 根因

多个协程并发访问同一变量，且至少有一个写操作，没有同步机制。

## 版本兼容性

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

## 解决方案

1. **Use sync.Mutex to protect shared variable** (98% 成功率)
   ```
   var mu sync.Mutex
var counter int
for i := 0; i < 10; i++ {
    go func() {
        mu.Lock()
        counter++
        mu.Unlock()
    }()
}
   ```
2. **Use atomic operations for simple types** (95% 成功率)
   ```
   var counter int64
for i := 0; i < 10; i++ {
    go func() {
        atomic.AddInt64(&counter, 1)
    }()
}
   ```

## 无效尝试

- **Ignoring the race warning** — Data races lead to undefined behavior, crashes, or corrupted data. (95% 失败率)
- **Using time.Sleep to synchronize** — Sleep does not guarantee ordering or atomicity; races persist. (90% 失败率)
