go runtime_error ai_generated true

致命错误: 并发遍历 map 与写 map

fatal error: concurrent map iteration and map write

ID: go/concurrent-map-iteration-and-write

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-06-03首次发现

版本兼容性

版本状态引入弃用备注
1.0+ active — — —

根因分析

一个 goroutine 用 range 遍历 map,同时另一个 goroutine 写入该 map,运行时将其视为致命竞争。

English

A goroutine iterates a map with range while another goroutine writes to it, which the runtime flags as a fatal race.

generic

解决方案

  1. 93% 成功率
    Hold an RWMutex read lock for the whole iteration and use a write lock for mutations.
  2. 88% 成功率
    Snapshot the map under a lock into a plain slice, then iterate the slice outside the lock.

无效尝试

常见但无效的做法:

  1. 70% 失败

    The write still races with the copy loop and can panic during the copy itself.