go runtime_error ai_generated true

警告:数据竞争:协程X写入,协程Y读取(全局变量)

WARNING: DATA RACE: Write by goroutine X, Read by goroutine Y (global variable)

ID: go/goroutine-racy-global-variable

其他格式: JSON · Markdown 中文 · English
80%修复率
89%置信度
0证据数
2026-04-18首次发现

版本兼容性

版本状态引入弃用备注
1.0 active
1.22 active

根因分析

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

English

Multiple goroutines accessing a global variable without synchronization.

generic

解决方案

  1. 95% 成功率 Use sync.Mutex to protect global variable
    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. 90% 成功率 Use atomic.Value for global state
    var global atomic.Value
    global.Store(42)
    val := global.Load().(int)

无效尝试

常见但无效的做法:

  1. Using global variable with local copy 90% 失败

    Local copy doesn't protect global; race still on global.

  2. Using atomic.Load/Store on non-atomic variable 70% 失败

    Variable must be of atomic type; int64 works, but struct doesn't.