go
runtime_error
ai_generated
true
致命错误:并发slice追加
fatal error: concurrent slice append
ID: go/goroutine-racy-slice-append
80%修复率
85%置信度
0证据数
2024-10-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
多个协程向同一个slice追加元素而没有同步,导致数据竞争。
English
Multiple goroutines appending to the same slice without synchronization, causing data race.
解决方案
-
90% 成功率 Use mutex to protect slice append
var mu sync.Mutex var s []int mu.Lock() s = append(s, 1) mu.Unlock()
-
85% 成功率 Use channel to collect results
ch := make(chan int, 10) for i := 0; i < 10; i++ { go func(val int) { ch <- val }(i) } var s []int for i := 0; i < 10; i++ { s = append(s, <-ch) }
无效尝试
常见但无效的做法:
-
Pre-allocating slice with make to avoid reallocation
80% 失败
Append still modifies slice header; concurrent writes race on length.
-
Using copy-on-write pattern manually
70% 失败
Complex and error-prone; still racy without synchronization.