go
runtime_error
ai_generated
true
警告:数据竞争(协程读操作)
WARNING: DATA RACE (goroutine read)
ID: go/goroutine-race-condition-read
80%修复率
86%置信度
0证据数
2024-10-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
一个协程读取变量时,另一个协程在无同步的情况下写入该变量。
English
A goroutine reads a variable while another goroutine writes to it without synchronization.
解决方案
-
97% 成功率 Use sync.RWMutex for read preference
var mu sync.RWMutex var data map[string]int read := func(key string) int { mu.RLock() defer mu.RUnlock() return data[key] } write := func(key string, val int) { mu.Lock() defer mu.Unlock() data[key] = val } -
95% 成功率 Use channels to communicate instead of shared memory
ch := make(chan int) go func() { v := <-ch // use v }() ch <- 42
无效尝试
常见但无效的做法:
-
Using a local copy of the variable
70% 失败
The copy is made before the write, but the race still exists at the read point.
-
Adding more goroutines to distribute load
85% 失败
More goroutines increase the chance of race conditions.