go runtime_error ai_generated true

fatal error: concurrent map read and map write

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

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.21 active
1.22 active

Root Cause

One goroutine reads from a map while another goroutine writes to it without synchronization.

generic

中文

一个协程读取map时,另一个协程在无同步的情况下写入该map。

Workarounds

  1. 97% success Use sync.RWMutex for read-write protection
    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. 95% success Use a single goroutine to own the map and communicate via channels
    ch := make(chan request)
    go func() {
        m := make(map[string]int)
        for req := range ch {
            switch req.op {
            case "read":
                req.resp <- m[req.key]
            case "write":
                m[req.key] = req.val
            }
        }
    }()

Dead Ends

Common approaches that don't work:

  1. Using a read-only copy of the map 75% fail

    Copying a map during concurrent writes is also racy.

  2. Using a channel to serialize access 60% fail

    If not done correctly, it can introduce deadlocks.