go
runtime_error
ai_generated
true
fatal error: 并发读写 map
fatal error: concurrent map read and map write
ID: go/fatal-error-concurrent-map-read-and-map-write
80%修复率
87%置信度
0证据数
2024-04-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.17 | active | — | — | — |
| 1.20 | active | — | — | — |
| 1.23 | active | — | — | — |
根因分析
一个 goroutine 读取 map 的同时另一个 goroutine 写入该 map,且没有加锁;运行时检测到不安全的访问模式并终止进程。
English
One goroutine reads a map while another writes it, without a lock; the runtime detects the unsafe access pattern and aborts.
解决方案
-
96% 成功率
var mu sync.RWMutex mu.RLock() v := m[k] mu.RUnlock() mu.Lock() m[k] = v2 mu.Unlock()
-
90% 成功率
var m sync.Map m.Load(k) m.Store(k, v)
无效尝试
常见但无效的做法:
-
85% 失败
Copying itself iterates the map while it is written, still triggering the fatal error.
-
90% 失败
Reads still race with writes; the runtime aborts on the read/write overlap.