go
runtime_error
ai_generated
true
致命错误:并发 slice 读取和 slice 写入
fatal error: concurrent slice read and slice write
ID: go/racy-slice-access
80%修复率
85%置信度
0证据数
2024-11-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
多个 goroutine 在没有同步的情况下访问同一个 slice,导致数据竞态。
English
Multiple goroutines access the same slice without synchronization, causing data races.
解决方案
-
95% 成功率 Use a mutex to synchronize all accesses
var mu sync.Mutex mu.Lock() slice[i] = value mu.Unlock()
-
90% 成功率 Use atomic operations for simple types
var val atomic.Value val.Store(mySlice) // then load and use
无效尝试
常见但无效的做法:
-
Using a channel to pass slice elements
80% 失败
If the underlying slice is still shared, races can occur on the backing array.
-
Copying the slice before writing
75% 失败
Shallow copy shares the underlying array; deep copy needed.