go
runtime_error
ai_generated
true
fatal error: concurrent map iteration and map write
ID: go/racy-map-access
80%Fix Rate
85%Confidence
0Evidence
2024-10-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.6 | active | — | — | — |
| 1.21 | active | — | — | — |
Root Cause
One goroutine is iterating over a map while another goroutine writes to it, causing a race condition.
generic中文
一个 goroutine 正在迭代 map,而另一个 goroutine 正在写入该 map,导致竞态条件。
Workarounds
-
95% success Use sync.RWMutex to protect both reads and writes
var mu sync.RWMutex mu.RLock() for k, v := range myMap { ... } mu.RUnlock() mu.Lock() myMap[key] = value mu.Unlock() -
90% success Use sync.Map for concurrent-safe map operations
var m sync.Map m.Store(key, value) m.Load(key)
Dead Ends
Common approaches that don't work:
-
Using a sync.Mutex only around writes
85% fail
Iteration also needs protection; concurrent iteration and write still race.
-
Using a RWMutex for reads but not for iteration
80% fail
Iteration is a read operation but may still race with writes if not locked.