go runtime_error ai_generated true

fatal error: concurrent slice append

ID: go/goroutine-race-on-slice

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Multiple goroutines append to the same slice concurrently without synchronization, causing data races and potential panics.

generic

中文

多个 goroutine 同时向同一个切片追加数据而没有同步,导致数据竞争和潜在的恐慌。

Workarounds

  1. 95% success
    var mu sync.Mutex; mu.Lock(); slice = append(slice, item); mu.Unlock()
  2. 90% success
    ch := make(chan int); go func() { for v := range ch { slice = append(slice, v) } }()

Dead Ends

Common approaches that don't work:

  1. 70% fail

    If slice is also accessed directly, race persists.

  2. 85% fail

    Atomic operations don't help with slice growth; underlying array may be replaced.