go runtime_error ai_generated true

致命错误:并发切片写入

fatal error: concurrent slice writes

ID: go/goroutine-slice-append-race

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

版本兼容性

版本状态引入弃用备注
1.20 active
1.21 active

根因分析

多个协程在没有同步的情况下追加到同一个切片,导致数据竞争。

English

Multiple goroutines append to the same slice without synchronization, causing a data race.

generic

解决方案

  1. 95% 成功率 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()
    }
  2. 90% 成功率 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)
    }

无效尝试

常见但无效的做法:

  1. Using a channel to serialize appends but not draining the channel properly. 70% 失败

    If channel is buffered and not drained, goroutines may block or deadlock.

  2. Assuming append is atomic. 90% 失败

    append is not atomic; it may read and update the slice header concurrently, causing corruption.