go runtime_error ai_generated true

fatal error: 并发 map 迭代和写入

fatal error: concurrent map iteration and map write

ID: go/concurrent-map-iterations

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

版本兼容性

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

根因分析

某 goroutine 使用 for range 迭代 map,同时另一 goroutine 向同一 map 写入,运行时检测到后直接终止。

English

A goroutine iterates a map with for range while another goroutine writes to the same map, which the runtime detects and aborts.

generic

解决方案

  1. 97% 成功率
    mu.Lock()
    for k, v := range m { process(k, v) }
    mu.Unlock()
  2. 93% 成功率
    type req struct{ reply chan map[string]int }
    for r := range reqs { r.reply <- snapshot(m) }

无效尝试

常见但无效的做法:

  1. 88% 失败

    Copying without locking still races with the writer during the copy itself.

  2. 86% 失败

    Taking the snapshot races with concurrent writes and can still trigger the detector.