go
runtime_error
ai_generated
true
致命错误:并发 map 迭代和 map 写入
fatal error: concurrent map iteration and map write
ID: go/racy-map-access
80%修复率
85%置信度
0证据数
2024-10-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.6 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
一个 goroutine 正在迭代 map,而另一个 goroutine 正在写入该 map,导致竞态条件。
English
One goroutine is iterating over a map while another goroutine writes to it, causing a race condition.
解决方案
-
95% 成功率 Use sync.RWMutex to protect both reads and writes
var mu sync.RWMutex mu.RLock() for k, v := range myMap { ... } mu.RUnlock() mu.Lock() myMap[key] = value mu.Unlock() -
90% 成功率 Use sync.Map for concurrent-safe map operations
var m sync.Map m.Store(key, value) m.Load(key)
无效尝试
常见但无效的做法:
-
Using a sync.Mutex only around writes
85% 失败
Iteration also needs protection; concurrent iteration and write still race.
-
Using a RWMutex for reads but not for iteration
80% 失败
Iteration is a read operation but may still race with writes if not locked.