Concurrent access of maps
suggest changeMaps in Go are not safe for concurrency.
One option to ensure safe concurrent access is to use sync.Mutex or sync.RWMutex and lock around all map reads and writes.
As an example, a wrapper around a map that is safe for concurrent use when all access goes through Get, Set, and Add:
package main
import (
"fmt"
"sync"
)
// ConcurrentMap is a wrapper around map that is safe for concurrent use
type ConcurrentMap struct {
sync.RWMutex
m map[string]int
}
// Get gets a value for a key
func (r *ConcurrentMap) Get(key string) int {
r.RLock()
defer r.RUnlock()
return r.m[key]
}
// Set sets a key to a given value
func (r *ConcurrentMap) Set(key string, val int) {
r.Lock()
defer r.Unlock()
r.m[key] = val
}
// Add increases the value under a key by n
func (r *ConcurrentMap) Add(key string, n int) int {
r.Lock()
defer r.Unlock()
r.m[key] += n
return r.m[key]
}
func main() {
counter := ConcurrentMap{m: make(map[string]int)}
n := counter.Add("some_key", 2)
fmt.Printf("Final value is: %d\n", n)
}
Final value is: 2
sync.RWMutex can be faster because it allows multiple readers. Do not write while holding RLock. The difference from sync.Mutex is negligible unless the lock is highly contended or held for a long time.
Embedding sync.RWMutex promotes Lock and Unlock, so those methods are part of ConcurrentMap's exported API. A named mutex field keeps them unexported.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents