go
runtime_error
ai_generated
true
fatal error: concurrent map iteration and map write
ID: go/concurrent-map-iteration-and-write
80%Fix Rate
88%Confidence
0Evidence
2024-06-03First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.0+ | active | — | — | — |
Root Cause
A goroutine iterates a map with range while another goroutine writes to it, which the runtime flags as a fatal race.
generic中文
一个 goroutine 用 range 遍历 map,同时另一个 goroutine 写入该 map,运行时将其视为致命竞争。
Workarounds
-
93% success
Hold an RWMutex read lock for the whole iteration and use a write lock for mutations.
-
88% success
Snapshot the map under a lock into a plain slice, then iterate the slice outside the lock.
Dead Ends
Common approaches that don't work:
-
70% fail
The write still races with the copy loop and can panic during the copy itself.