go runtime_error ai_generated true

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

ID: go/goroutine-racy-global-variable

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2026-04-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.22 active

Root Cause

Multiple goroutines accessing a global variable without synchronization.

generic

中文

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

Workarounds

  1. 95% success 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% success Use atomic.Value for global state
    var global atomic.Value
    global.Store(42)
    val := global.Load().(int)

Dead Ends

Common approaches that don't work:

  1. Using global variable with local copy 90% fail

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

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

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