go runtime_error ai_generated true

WARNING: DATA RACE 由 goroutine N 在 0x... 读取: runtime.growslice() 由 goroutine M 在 0x... 之前写入: main.append()

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

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-04-18首次发现

版本兼容性

版本状态引入弃用备注
1.18 active — — —
1.22 active — — —

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 85% 失败

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

  2. 80% 失败

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