go runtime_error ai_generated true

致命错误:并发 map 读取和 map 写入

fatal error: concurrent map read and map write

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

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

版本兼容性

版本状态引入弃用备注
1.18 active
1.19 active
1.20 active
1.21 active

根因分析

一个协程从 map 中读取,而另一个协程在没有同步的情况下写入 map,导致数据竞争。

English

One goroutine reads from a map while another writes to it without synchronization, causing a data race.

generic

解决方案

  1. 95% 成功率 Use sync.RWMutex to protect both reads and writes
    var mu sync.RWMutex
    mu.RLock()
    val := myMap[key]
    mu.RUnlock()
  2. 90% 成功率 Use sync.Map for concurrent read/write
    var m sync.Map
    m.Load(key) // safe concurrent read

无效尝试

常见但无效的做法:

  1. Use a read-write lock (sync.RWMutex) only for writes 60% 失败

    If reads are not protected, they can still race with writes.

  2. Use a copy of the map for reads 90% 失败

    Copying a map while it is being written is unsafe and can cause a race.