go runtime_error ai_generated true

fatal error: concurrent map writes

ID: go/race-condition-shared-map

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.21 active

Root Cause

Multiple goroutines writing to the same map without synchronization causes a runtime crash.

generic

中文

多个 goroutine 在没有同步的情况下写入同一个映射会导致运行时崩溃。

Workarounds

  1. 95% success
    var mu sync.RWMutex
    m := make(map[string]int)
    // Write
    mu.Lock()
    m["key"] = 1
    mu.Unlock()
    // Read
    mu.RLock()
    val := m["key"]
    mu.RUnlock()
  2. 90% success
    var m sync.Map
    m.Store("key", 1)
    val, _ := m.Load("key")

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Concurrency issue is not about collisions; it's about data races.

  2. 70% fail

    sync.Map is safe for concurrent writes, but if mixed with regular map, issue persists.

  3. 95% fail

    Sleeps don't synchronize; race remains.