Golang / GoLang Concurrency Mastery Interview Questions
How do you safely use a map from multiple goroutines in Go?
Go maps are not safe for concurrent use. The runtime detects concurrent map access and throws a fatal error: 'concurrent map read and map write'. There are three main solutions, each with different performance trade-offs.
// BUGGY: concurrent map access â runtime fatal error var m = map[string]int{} for i := 0; i < 100; i++ { go func(n int) { m[fmt.Sprint(n)] = n // RACE: concurrent write }(i) } // SOLUTION 1: sync.Mutex protecting a regular 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 } // SOLUTION 2: sync.Map (optimised for read-heavy / disjoint-key patterns) var sm sync.Map sm.Store("key", 42) val, ok := sm.Load("key") sm.Delete("key") sm.Range(func(k, v any) bool { fmt.Println(k, v) return true // return false to stop }) // SOLUTION 3: actor model â single goroutine owns the map type op struct{ key string; val int; resp chan int } opCh := make(chan op) go func() { m := map[string]int{} for o := range opCh { m[o.key] = o.val if o.resp != nil { o.resp <- m[o.key] } } }()
More Related questions...