go runtime_error ai_generated true

WARNING: DATA RACE 写操作 0x00c000... 由 goroutine 7 执行 先前的写操作 0x00c000... 由 goroutine 8 执行

WARNING: DATA RACE Write at 0x00c000... by goroutine 7 Previous write at 0x00c000... by goroutine 8

ID: go/race-detector-write-write

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

版本兼容性

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

根因分析

两个 goroutine 在没有同步的情况下访问同一内存位置,且至少有一次写操作,在 -race 模式下被竞态检测器捕获。

English

Two goroutines access the same memory location without synchronization, with at least one write, detected by the race detector when running with -race.

generic

解决方案

  1. 95% 成功率
    var mu sync.Mutex
    mu.Lock()
    counter++
    mu.Unlock()
    // or
    atomic.AddInt64(&counter, 1)
  2. 92% 成功率
    results := make(chan int, len(items))
    for _, it := range items {
        it := it
        go func(v int) { results <- compute(v) }(it)
    }

无效尝试

常见但无效的做法:

  1. 95% 失败

    The race is real; disabling detection does not fix corruption, which surfaces later as random crashes.

  2. 90% 失败

    Sleep reduces the window but does not eliminate the race; the detector still reports it.