go runtime_error ai_generated true

fatal error: concurrent map read and map write

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

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.21 active — — —

Root Cause

One goroutine reads a map while another writes it. The runtime's map race detector fires and crashes the process.

generic

中文

一个 goroutine 读取 map 的同时另一个 goroutine 写入该 map。运行时的 map 竞争检测器触发并导致进程崩溃。

Workarounds

  1. 95% success
    Use sync.RWMutex: mu.RLock() for reads, mu.Lock() for writes; ensure reads also hold the lock
  2. 85% success
    Pass map snapshots through channels so only one goroutine owns the map

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Reads racing writes still trigger the fatal error

  2. 85% fail

    The copy itself iterates the map while it is being written, still racing