go runtime_error ai_generated true

fatal error: 并发读写 map

fatal error: concurrent map read and map write

ID: go/concurrent-map-read-write

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

版本兼容性

版本状态引入弃用备注
1.0+ active

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 80% 失败

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

  2. 70% 失败

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