go runtime_error ai_generated true

fatal error: concurrent map iteration and map write

ID: go/concurrent-map-write-during-range

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-02-27First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.21 active — — —
1.22 active — — —

Root Cause

A map is being range-iterated in one goroutine while another goroutine writes to the same map, violating Go's map safety rules.

generic

中文

一个 goroutine 正在 range 遍历 map,同时另一个 goroutine 写入同一个 map,违反了 Go 的 map 安全规则。

Workarounds

  1. 97% success
    var mu sync.RWMutex
    mu.RLock()
    for k, v := range m { _ = k; _ = v }
    mu.RUnlock()
    // writer:
    mu.Lock()
    m[k] = v
    mu.Unlock()
  2. 90% success
    var m sync.Map
    m.Range(func(k, v any) bool { return true })
    m.Store(key, val)

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Timing-based avoidance is unreliable; the runtime can still detect concurrent access under load.

  2. 95% fail

    This is a fatal runtime error, not a panic; recover cannot catch it and the process exits.