go
runtime_error
ai_generated
true
fatal error: concurrent map read and map write
ID: go/goroutine-map-concurrent-read-and-write
80%Fix Rate
85%Confidence
0Evidence
2024-10-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.19 | active | — | — | — |
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
Root Cause
One goroutine reads from a map while another writes to it without synchronization, causing a data race.
generic中文
一个协程从 map 中读取,而另一个协程在没有同步的情况下写入 map,导致数据竞争。
Workarounds
-
95% success Use sync.RWMutex to protect both reads and writes
var mu sync.RWMutex mu.RLock() val := myMap[key] mu.RUnlock()
-
90% success Use sync.Map for concurrent read/write
var m sync.Map m.Load(key) // safe concurrent read
Dead Ends
Common approaches that don't work:
-
Use a read-write lock (sync.RWMutex) only for writes
60% fail
If reads are not protected, they can still race with writes.
-
Use a copy of the map for reads
90% fail
Copying a map while it is being written is unsafe and can cause a race.