go runtime_error ai_generated true

WARNING: DATA RACE Goroutine 7 在 0x00c0000b4010 处写入:

WARNING: DATA RACE Write at 0x00c0000b4010 by goroutine 7:

ID: go/data-race-detector-warning

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

版本兼容性

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

根因分析

两个 goroutine 并发访问同一内存位置,至少一个是写操作,且没有同步机制排序。仅在 -race 构建时被检测到;否则程序行为未定义。

English

Two goroutines access the same memory location concurrently, at least one is a write, and no synchronization orders them. Detected only when built with -race; the program otherwise has undefined behavior.

generic

解决方案

  1. 95% 成功率
    Protect the shared variable with a mutex:
    
    var mu sync.Mutex
    mu.Lock()
    counter++
    mu.Unlock()
  2. 92% 成功率
    Use atomic operations for simple counters:
    
    var counter int64
    atomic.AddInt64(&counter, 1)
    _ = atomic.LoadInt64(&counter)

无效尝试

常见但无效的做法:

  1. 95% 失败

    Hiding the report does not fix the race; the bug persists and manifests as corrupted data or crashes in production.

  2. 90% 失败

    Sleep reduces the probability but does not establish a happens-before relationship; the race and its undefined behavior remain.