go runtime_error ai_generated true

WARNING: DATA RACE Read at 0x... by goroutine N: runtime.growslice() Previous write at 0x... by goroutine M: main.append()

ID: go/race-detector-unsynchronized-slice-append

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.22 active — — —

Root Cause

Multiple goroutines call append() on the same slice header without synchronization, causing races on the backing array and length field.

generic

中文

多个 goroutine 在无同步的情况下对同一个 slice 头调用 append(),导致对底层数组和长度字段的竞态。

Workarounds

  1. 95% success
    var mu sync.Mutex
    var out []T
    mu.Lock()
    out = append(out, v)
    mu.Unlock()
  2. 93% success
    results := make(chan T, n)
    // producers: results <- v
    // consumer: for v := range results { out = append(out, v) }

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Preallocation avoids reallocation but the length field and slots are still written concurrently.

  2. 80% fail

    Concurrent writes to distinct indices of the same array are still data races unless synchronized.