go
runtime_error
ai_generated
true
警告:数据竞争(协程写操作)
WARNING: DATA RACE (goroutine write)
ID: go/goroutine-race-condition-write
80%修复率
88%置信度
0证据数
2024-09-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
多个协程并发访问同一变量,且至少有一个写操作,没有同步机制。
English
Multiple goroutines access the same variable concurrently, with at least one write, without synchronization.
解决方案
-
98% 成功率 Use sync.Mutex to protect shared variable
var mu sync.Mutex var counter int for i := 0; i < 10; i++ { go func() { mu.Lock() counter++ mu.Unlock() }() } -
95% 成功率 Use atomic operations for simple types
var counter int64 for i := 0; i < 10; i++ { go func() { atomic.AddInt64(&counter, 1) }() }
无效尝试
常见但无效的做法:
-
Ignoring the race warning
95% 失败
Data races lead to undefined behavior, crashes, or corrupted data.
-
Using time.Sleep to synchronize
90% 失败
Sleep does not guarantee ordering or atomicity; races persist.