Junior — Middle
How to ensure the safety of working with Map in a multithreaded environment?
sobes.tech AI
Answer from AI
In Go, the standard map is not thread-safe for concurrent read and write operations from different goroutines. To ensure safety when working with maps in a multithreaded environment, you can use:
- Mutexes (sync.Mutex or sync.RWMutex) — block access to the map during read/write.
var (
m = make(map[string]int)
mu sync.RWMutex
)
func read(key string) int {
mu.RLock()
defer mu.RUnlock()
return m[key]
}
func write(key string, value int) {
mu.Lock()
defer mu.Unlock()
m[key] = value
}
- sync.Map — a specialized thread-safe structure from the standard library, optimized for cases with many goroutines.
var m sync.Map
func write(key string, value int) {
m.Store(key, value)
}
func read(key string) (int, bool) {
val, ok := m.Load(key)
if !ok {
return 0, false
}
return val.(int), true
}
The choice depends on the specific task: if many write and read operations are needed, it's better to use mutexes; if read operations predominate, sync.Map can be more efficient.