go
runtime_error
ai_generated
true
fatal error: concurrent map iteration and map write
ID: go/fatal-error-concurrent-map-iteration-and-map-write
80%Fix Rate
90%Confidence
0Evidence
2024-06-18First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
One goroutine ranges over a map while another goroutine writes to it, which the runtime detects and aborts.
generic中文
一个 goroutine 正在 range 遍历 map,同时另一个 goroutine 写入该 map,运行时检测到并中止。
Workarounds
-
92% success
Hold a sync.RWMutex: mu.RLock(); for k, v := range m { ... }; mu.RUnlock(), and mu.Lock() for writes. -
90% success
Snapshot under lock: mu.RLock(); snapshot := make(map[K]V, len(m)); for k, v := range m { snapshot[k] = v }; mu.RUnlock(); then range over snapshot.
Dead Ends
Common approaches that don't work:
-
85% fail
The copy itself races with the writer; the runtime aborts during the copy loop.
-
90% fail
Maps have no index operator; this does not compile, and even an equivalent iteration still races.