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
92%Confidence
0Evidence
2024-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

One goroutine read a map while another wrote to it. Go's runtime map has no internal locking and aborts on detected read/write races.

generic

中文

一个 goroutine 读 map 的同时另一个 goroutine 写该 map。Go 运行时 map 无内置锁,检测到读写竞态即终止。

Workarounds

  1. 97% success
    var mu sync.RWMutex
    func get(k string) (V, bool) {
        mu.RLock(); defer mu.RUnlock()
        v, ok := m[k]; return v, ok
    }
    func set(k string, v V) {
        mu.Lock(); defer mu.Unlock()
        m[k] = v
    }
  2. 92% success
    type shard struct { mu sync.RWMutex; m map[string]V }
    shards := make([]shard, 32)
    idx := fnv32(k) % 32
    shards[idx].mu.Lock()
    shards[idx].m[k] = v
    shards[idx].mu.Unlock()

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Struct fields are not atomic; concurrent access still races and may not even be detected, causing silent corruption.

  2. 70% fail

    The race detector adds large overhead and must be built in; it does not prevent the fatal error in non-race builds.