go runtime_error ai_generated true

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

ID: go/goroutine-race-on-closure-variable

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2025-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active — — —
1.22 active — — —

Root Cause

Goroutine closures capture loop variables by reference, causing multiple goroutines to race on the same variable.

generic

中文

协程闭包通过引用捕获循环变量,导致多个协程竞争同一个变量。

Workarounds

  1. 99% success Pass loop variable as argument to goroutine
    for i := 0; i < 10; i++ {
        go func(val int) {
            fmt.Println(val)
        }(i)
    }
  2. 98% success Create local copy within loop
    for i := 0; i < 10; i++ {
        val := i
        go func() {
            fmt.Println(val)
        }()
    }

Dead Ends

Common approaches that don't work:

  1. Adding time.Sleep in loop to stagger goroutines 90% fail

    Race condition still exists; timing-dependent fix unreliable.

  2. Using global variable instead of local 80% fail

    Global variable is shared; race condition worsens.