go runtime_error ai_generated true

致命错误:并发map读写操作

fatal error: concurrent map read and map write

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

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-12-01首次发现

版本兼容性

版本状态引入弃用备注
1.21 active
1.22 active

根因分析

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

English

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

generic

解决方案

  1. 97% 成功率 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% 成功率 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
            }
        }
    }()

无效尝试

常见但无效的做法:

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

    Copying a map during concurrent writes is also racy.

  2. Using a channel to serialize access 60% 失败

    If not done correctly, it can introduce deadlocks.