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
80%Fix Rate
90%Confidence
0Evidence
2025-01-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
99% success Pass loop variable as argument to goroutine
for i := 0; i < 10; i++ { go func(val int) { fmt.Println(val) }(i) } -
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:
-
Adding time.Sleep in loop to stagger goroutines
90% fail
Race condition still exists; timing-dependent fix unreliable.
-
Using global variable instead of local
80% fail
Global variable is shared; race condition worsens.