Maps 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 simple wrapper around a map
that is safe for concurrent use as long as it's done by Get
, Set
and Add
methods:
https://codeeval.dev/gist/02626d95a38e8c56a94032292f452a3b
sync.RWMutex
can be faster because it allows multiple readers. On the downside you have to be more careful to ensure you're not writing under RLock
. The performance difference with sync.Mutex
will be negligible unless there's a high-contention on the lock or the locks are held for a long time.