go
runtime_error
ai_generated
true
致命错误:并发map读写操作
fatal error: concurrent map read and map write
ID: go/goroutine-map-concurrent-read-write
80%修复率
88%置信度
0证据数
2024-12-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
一个协程读取map时,另一个协程在无同步的情况下写入该map。
English
One goroutine reads from a map while another goroutine writes to it without synchronization.
解决方案
-
97% 成功率 Use sync.RWMutex for read-write protection
var mu sync.RWMutex m := make(map[string]int) // write mu.Lock() m["key"] = 1 mu.Unlock() // read mu.RLock() val := m["key"] mu.RUnlock()
-
95% 成功率 Use a single goroutine to own the map and communicate via channels
ch := make(chan request) go func() { m := make(map[string]int) for req := range ch { switch req.op { case "read": req.resp <- m[req.key] case "write": m[req.key] = req.val } } }()
无效尝试
常见但无效的做法:
-
Using a read-only copy of the map
75% 失败
Copying a map during concurrent writes is also racy.
-
Using a channel to serialize access
60% 失败
If not done correctly, it can introduce deadlocks.