# 警告：数据竞争：协程X写入，协程Y读取（全局变量）

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

## 根因

多个协程在没有同步的情况下访问全局变量。

## 版本兼容性

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

## 解决方案

1. **Use sync.Mutex to protect global variable** (95% 成功率)
   ```
   var mu sync.Mutex
var global int
func setGlobal(v int) {
    mu.Lock()
    global = v
    mu.Unlock()
}
func getGlobal() int {
    mu.Lock()
    defer mu.Unlock()
    return global
}
   ```
2. **Use atomic.Value for global state** (90% 成功率)
   ```
   var global atomic.Value
global.Store(42)
val := global.Load().(int)
   ```

## 无效尝试

- **Using global variable with local copy** — Local copy doesn't protect global; race still on global. (90% 失败率)
- **Using atomic.Load/Store on non-atomic variable** — Variable must be of atomic type; int64 works, but struct doesn't. (70% 失败率)
