go runtime_error ai_generated true

警告:数据竞争 - goroutine 6 在地址 0x00c000012345 写入

WARNING: DATA RACE - Write at 0x00c000012345 by goroutine 6

ID: go/data-race-on-variable

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

版本兼容性

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

根因分析

并发读写共享变量而没有同步。

English

Concurrent reads and writes to a shared variable without synchronization.

generic

解决方案

  1. 95% 成功率
    var mu sync.Mutex
    var x int
    // Write
    mu.Lock()
    x = 1
    mu.Unlock()
    // Read
    mu.Lock()
    _ = x
    mu.Unlock()
  2. 90% 成功率
    var x atomic.Int32
    x.Store(1)
    _ = x.Load()

无效尝试

常见但无效的做法:

  1. 50% 失败

    Reads still race unless also atomic.

  2. 100% 失败

    Go doesn't have volatile; no effect.

  3. 90% 失败

    Sleep doesn't establish happens-before relationship.