go runtime_error ai_generated true

fatal error: 并发 map 迭代与写入

fatal error: concurrent map iteration and map write

ID: go/concurrent-map-iteration-write

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

版本兼容性

版本状态引入弃用备注
1.19 active — — —
1.21 active — — —
1.22 active — — —

根因分析

对 map 的 range 迭代与另一个 goroutine 对同一 map 的写入并发执行。运行时检测到迭代器与写入冲突后终止程序。

English

A range loop over a map runs concurrently with a write to the same map in another goroutine. The runtime detects the iterator/writer conflict and aborts.

generic

解决方案

  1. 95% 成功率
    Hold a read lock for the whole iteration and a write lock for mutations:
    
    s.mu.RLock()
    for k, v := range s.m {
        _ = k; _ = v
    }
    s.mu.RUnlock()
  2. 90% 成功率
    Snapshot keys under lock, then iterate the snapshot:
    
    s.mu.RLock()
    keys := make([]string, 0, len(s.m))
    for k := range s.m { keys = append(keys, k) }
    s.mu.RUnlock()
    for _, k := range keys { _ = k }

无效尝试

常见但无效的做法:

  1. 90% 失败

    Assigning a map copies only the header, not the contents; both variables share the same underlying map, so writes still race with iteration.

  2. 88% 失败

    Sleeping widens or shifts the race window but does not synchronize; the fatal error still occurs under load.