go
runtime_error
ai_generated
true
fatal error: concurrent slice writes
ID: go/goroutine-slice-append-race
80%Fix Rate
86%Confidence
0Evidence
2024-11-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
Root Cause
Multiple goroutines append to the same slice without synchronization, causing a data race.
generic中文
多个协程在没有同步的情况下追加到同一个切片,导致数据竞争。
Workarounds
-
95% success Use a mutex to protect slice appends.
var mu sync.Mutex var slice []int func appendValue(v int) { mu.Lock() slice = append(slice, v) mu.Unlock() } -
90% success Use a channel to aggregate results from goroutines.
ch := make(chan int, 100) for i := 0; i < n; i++ { go func() { ch <- compute() }() } var results []int for i := 0; i < n; i++ { results = append(results, <-ch) }
Dead Ends
Common approaches that don't work:
-
Using a channel to serialize appends but not draining the channel properly.
70% fail
If channel is buffered and not drained, goroutines may block or deadlock.
-
Assuming append is atomic.
90% fail
append is not atomic; it may read and update the slice header concurrently, causing corruption.