gotchagoCritical
Concurrent map read/write causes panic
Viewed 0 times
concurrent mapmap panicsync.Mapmap read writethread-safe mapmap race
Error Messages
Problem
Reading and writing a Go map from multiple goroutines concurrently causes a runtime panic. Maps are not safe for concurrent use.
Solution
Protect map access with a mutex, or use sync.Map for concurrent use cases:
// Option 1: mutex-protected map
type SafeMap struct {
mu sync.RWMutex
m map[string]int
}
func (s *SafeMap) Set(k string, v int) {
s.mu.Lock()
defer s.mu.Unlock()
s.m[k] = v
}
func (s *SafeMap) Get(k string) (int, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
v, ok := s.m[k]
return v, ok
}
// Option 2: sync.Map (best for write-once, read-many or disjoint key sets)
var m sync.Map
m.Store("key", 42)
val, _ := m.Load("key")Why
Go's map implementation is not thread-safe by design for performance. The runtime detects concurrent map access and panics immediately rather than allowing undefined behaviour.
Gotchas
- The race detector will catch this before the panic in many cases — always run tests with -race
- sync.Map is not a drop-in replacement — it uses interface{} / any values and has different performance characteristics
- sync.Map performs best when keys are written once and read many times; for general use, a mutex-protected map is usually better
Revisions (0)
No revisions yet.