go runtime_error ai_generated true

fatal error: concurrent map read and map write

ID: go/fatal-error-concurrent-map-read-and-map-write

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-04-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.17 active — — —
1.20 active — — —
1.23 active — — —

Root Cause

One goroutine reads a map while another writes it, without a lock; the runtime detects the unsafe access pattern and aborts.

generic

中文

一个 goroutine 读取 map 的同时另一个 goroutine 写入该 map,且没有加锁;运行时检测到不安全的访问模式并终止进程。

Workarounds

  1. 96% success
    var mu sync.RWMutex
    mu.RLock()
    v := m[k]
    mu.RUnlock()
    mu.Lock()
    m[k] = v2
    mu.Unlock()
  2. 90% success
    var m sync.Map
    m.Load(k)
    m.Store(k, v)

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Copying itself iterates the map while it is written, still triggering the fatal error.

  2. 90% fail

    Reads still race with writes; the runtime aborts on the read/write overlap.