go
runtime_error
ai_generated
true
警告:数据竞争 Goroutine 7 在 0x00c0000b4010 处读取:
WARNING: DATA RACE Read at 0x00c0000b4010 by goroutine 7:
ID: go/data-race-detector
80%修复率
90%置信度
0证据数
2024-02-02首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.19 | active | — | — | — |
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
竞争检测器(go test -race / go run -race)发现对同一内存位置的无同步并发访问。通常是共享结构体字段或切片索引在无 mutex/atomic 保护下访问。
English
The race detector (go test -race / go run -race) found unsynchronized concurrent access to the same memory location. Usually a shared struct field or slice index accessed without a mutex or atomic.
解决方案
-
95% 成功率
var hits atomic.Int64 hits.Add(1) n := hits.Load()
-
97% 成功率
type Counter struct { mu sync.Mutex n int } func (c *Counter) Inc() { c.mu.Lock(); c.n++; c.mu.Unlock() } -
92% 成功率
results := make(chan Result) go func() { results <- compute() }() r := <-results // ownership transferred
无效尝试
常见但无效的做法:
-
95% 失败
Hides the bug; production crashes or corrupts state under real concurrency.
-
85% 失败
Does not establish happens-before; race remains and detector still fires.