go runtime_error ai_generated true

WARNING: DATA RACE 写操作地址 0x... 位于 goroutine N: main.foo() 此前的读操作地址 0x... 位于 goroutine M: main.bar()

WARNING: DATA RACE Write at 0x... by goroutine N: main.foo() Previous read at 0x... by goroutine M: main.bar()

ID: go/race-detector-warning

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

版本兼容性

版本状态引入弃用备注
1.1+ active

根因分析

两个 goroutine 在无同步的情况下访问同一内存位置,且至少有一个是写操作。仅在 -race 构建时能被检测到。

English

Two goroutines accessed the same memory location without synchronization, at least one being a write. Detected only when built with -race.

generic

解决方案

  1. 97% 成功率
    var mu sync.Mutex
    mu.Lock()
    counter++
    mu.Unlock()
    // or
    atomic.AddInt64(&counter, 1)
  2. 92% 成功率
    for _, item := range items {
        item := item // capture by value
        go func() { process(item) }()
    }

无效尝试

常见但无效的做法:

  1. 90% 失败

    Does not create a happens-before relationship between the two accesses; race detector still fires.

  2. 95% 失败

    Hides real bugs; production may corrupt data or crash non-deterministically.