go
runtime_error
ai_generated
true
警告:数据竞争:协程X写入,协程Y读取(闭包变量)
WARNING: DATA RACE: Write by goroutine X, Read by goroutine Y (closure variable)
ID: go/goroutine-race-on-closure-variable
80%修复率
90%置信度
0证据数
2025-01-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
协程闭包通过引用捕获循环变量,导致多个协程竞争同一个变量。
English
Goroutine closures capture loop variables by reference, causing multiple goroutines to race on the same variable.
解决方案
-
99% 成功率 Pass loop variable as argument to goroutine
for i := 0; i < 10; i++ { go func(val int) { fmt.Println(val) }(i) } -
98% 成功率 Create local copy within loop
for i := 0; i < 10; i++ { val := i go func() { fmt.Println(val) }() }
无效尝试
常见但无效的做法:
-
Adding time.Sleep in loop to stagger goroutines
90% 失败
Race condition still exists; timing-dependent fix unreliable.
-
Using global variable instead of local
80% 失败
Global variable is shared; race condition worsens.