go
runtime_error
ai_generated
true
致命错误:并发读 map 和写 map
fatal error: concurrent map read and map write
ID: go/concurrent-map-read-and-write
80%修复率
90%置信度
0证据数
2024-03-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
一个 goroutine 读 map 的同时另一个 goroutine 写同一个 map。运行时检测到这种不一致访问会终止程序。
English
One goroutine read a map while another wrote to it. The runtime's map implementation detects this inconsistent access and aborts the program.
解决方案
-
93% 成功率
var mu sync.RWMutex // writer mu.Lock(); m[k]=v; mu.Unlock() // reader mu.RLock(); v := m[k]; mu.RUnlock()
-
85% 成功率
type req struct{ key string; resp chan int } // single owner goroutine processes reqs serially
无效尝试
常见但无效的做法:
-
85% 失败
Copying a map being concurrently written also races and may panic or produce corrupted data.
-
87% 失败
Timing-based synchronization is unreliable and breaks under load or different GOMAXPROCS.