Junior — Middle
What are the differences between using a synchronized map and a mutex for managing access to shared data in Go?
sobes.tech AI
Answer from AI
In Go, access to shared data is often managed using either synchronized data structures (e.g., sync.Map) or mutexes (sync.Mutex).
Differences:
-
sync.Map is a specialized thread-safe map optimized for scenarios with many read operations and fewer writes. It implements internal synchronization mechanisms and is suitable when you need to read data frequently without locking the entire structure.
-
sync.Mutex is a locking primitive that allows you to manually protect any data (including regular
mapmaps) from concurrent access. When using a mutex, you control the critical section by locking and unlocking.
When to use what:
- If you have a simple case with frequent reads and rare writes, and need a thread-safe map —
sync.Mapis better. - If you need more flexible logic, or more complex operations, or want to control locking — use
sync.Mutexwith a regular map.
Example with mutex:
var mu sync.Mutex
var m = make(map[string]int)
func write(key string, value int) {
mu.Lock()
defer mu.Unlock()
m[key] = value
}
func read(key string) (int, bool) {
mu.Lock()
defer mu.Unlock()
val, ok := m[key]
return val, ok
}
Example with sync.Map:
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
}