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] }
}
}()
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
