go runtime_error ai_generated true

fatal error: concurrent map read and map write

ID: go/concurrent-map-read-write

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.22 active — — —

Root Cause

One goroutine reads a map while another writes to it without a lock; runtime detects read/write race.

generic

中文

一个 goroutine 读取 map 的同时另一个写入,未加锁;运行时检测到读/写竞争。

Workarounds

  1. 95% success
    var mu sync.RWMutex
    mu.RLock()
    v := m[k]
    mu.RUnlock()
    // write:
    mu.Lock()
    m[k] = v
    mu.Unlock()
  2. 88% success
    var m sync.Map
    v, _ := m.Load(k)
    m.Store(k, v)

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Readers still race with writers; fatal error persists.

  2. 85% fail

    Copy itself races with the writer; still fatal.