go
runtime_error
ai_generated
true
fatal error: concurrent map iteration and map write
ID: go/concurrent-map-iteration-write
80%Fix Rate
90%Confidence
0Evidence
2024-06-19First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.19 | active | — | — | — |
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
A range loop over a map runs concurrently with a write to the same map in another goroutine. The runtime detects the iterator/writer conflict and aborts.
generic中文
对 map 的 range 迭代与另一个 goroutine 对同一 map 的写入并发执行。运行时检测到迭代器与写入冲突后终止程序。
Workarounds
-
95% success
Hold a read lock for the whole iteration and a write lock for mutations: s.mu.RLock() for k, v := range s.m { _ = k; _ = v } s.mu.RUnlock() -
90% success
Snapshot keys under lock, then iterate the snapshot: s.mu.RLock() keys := make([]string, 0, len(s.m)) for k := range s.m { keys = append(keys, k) } s.mu.RUnlock() for _, k := range keys { _ = k }
Dead Ends
Common approaches that don't work:
-
90% fail
Assigning a map copies only the header, not the contents; both variables share the same underlying map, so writes still race with iteration.
-
88% fail
Sleeping widens or shifts the race window but does not synchronize; the fatal error still occurs under load.