What is better to use for synchronization when working with concurrent access: mutex or sync.Map?
sobes.tech AI
Answer from AI
To synchronize concurrent access in Go, you can choose between mutex and sync.Map depending on the task:
-
sync.Mutexis a lock primitive that protects critical sections. It is versatile and suitable when you need to synchronize access to any data, especially if operations are complex or involve multiple data types. -
sync.Mapis a specialized data structure optimized for concurrent access to a map with frequent reads and infrequent writes. It implements internal synchronization mechanisms and is suitable when you need safe concurrent read/write without explicit mutexes.
If you have a simple map with frequent reads and rare writes, sync.Map can be more convenient and efficient. For more complex synchronization logic or different data types, use mutex.
Example with sync.Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
Example with sync.Map:
var m sync.Map
func storeValue(key string, value interface{}) {
m.Store(key, value)
}
func loadValue(key string) (interface{}, bool) {
return m.Load(key)
}
In summary: for general synchronization, use mutex; for concurrent map access, sync.Map.