tezvyn:

How do you safely share a Go map across goroutines?

AI-drafted, machine-checkedSource: pkg.go.devintermediate

Tests Go memory model. Answer: maps are not concurrency-safe and risk panic or corruption; use sync.RWMutex with map for read-heavy cases or sync.Map for cache-like patterns. Red flag: suggesting runtime.GOMAXPROCS or channel-only access without justification.

WHAT THIS TESTS: Whether you understand that Go maps are not concurrency-safe by design and that the runtime may detect concurrent writes and panic, or worse, silently corrupt memory. It also checks if you know the standard library synchronization primitives and can weigh sync.RWMutex against sync.Map based on workload characteristics.

A GOOD ANSWER COVERS: First, the candidate must state clearly that a plain map does not support concurrent access; even read-while-write is unsafe and can trigger a runtime panic with concurrent map writes or reads and map iteration. Second, they should present the idiomatic solution of wrapping the map in a struct with a sync.RWMutex, using Lock for writes and RLock for reads, which preserves type safety with map[string]int. Third, they should mention sync.Map as a built-in alternative optimized for cache-like scenarios with many reads and infrequent writes, but caution that it uses interface{} and loses compile-time type checking. Fourth, a strong candidate notes that if the goroutines are cooperative, a single goroutine owning the map and communicating via channels is another valid Go idiom, though it changes the architecture.

COMMON WRONG ANSWERS: Claiming that maps are safe if you only read and write different keys. Suggesting runtime.GOMAXPROCS(1) to avoid parallelism. Proposing a sync.Mutex without distinguishing read locks from write locks when reads dominate. Using sync.Map without acknowledging its type-erasure tradeoff or when it is slower than a mutex-wrapped map for small, type-safe structures.

LIKELY FOLLOW-UPS: How does sync.Map avoid contention compared to a mutex? When would you prefer a channel-based owner goroutine over a mutex? What happens if you copy a sync.Mutex or sync.Map value? How would you implement sharding to reduce lock contention?

ONE CONCRETE EXAMPLE: type SafeMap struct { mu sync.RWMutex; data map[string]int } func (s *SafeMap) Get(key string) (int, bool) { s.mu.RLock(); defer s.mu.RUnlock(); v, ok := s.data[key]; return v, ok } func (s *SafeMap) Set(key string, value int) { s.mu.Lock(); defer s.mu.Unlock(); s.data[key] = value }

Read the original → pkg.go.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.