Junior — Middle
When is it appropriate to use shared map with synchronization via mutexes?
sobes.tech AI
Answer from AI
In Go, the built-in map is not thread-safe, so concurrent access from multiple goroutines can lead to data races and panics.
Using a map with synchronization via mutexes is advisable when:
- You need to ensure safe concurrent access to a shared data map.
- Read and write operations on the map occur frequently from different goroutines.
- The volume of data and the frequency of operations are not so high as to justify using specialized thread-safe structures (e.g., sync.Map).
Example usage:
var mu sync.Mutex
var m = make(map[string]int)
func write(key string, value int) {
mu.Lock()
m[key] = value
mu.Unlock()
}
func read(key string) (int, bool) {
mu.Lock()
val, ok := m[key]
mu.Unlock()
return val, ok
}
If there are many operations and mostly reads, consider using sync.RWMutex or sync.Map.