I'm starting to use RWMutex
in my Go project with map
since now I have more than one routine running at the same time and while making all of the changes for that a doubt came to my mind.
The thing is that I know that we must use RLock
when only reading to allow other routines to do the same task and Lock
when writing to full-block the map. But what are we supposed to do when editing a previously created element in the map?
For example... Let's say I have a map[int]string
where I do Lock
, put inside "hello "
and then Unlock
. What if I want to add "world"
to it? Should I do Lock
or can I do RLock
?
You should approach the problem from another angle.
A simple rule of thumb you seem to understand just fine is
You need to protect the map from concurrent accesses when at least one of them is a modification.
Now the real question is what constitutes a modification of a map.
To answer it properly, it helps to notice that values stored in maps are not addressable — by design. This was engineered that way simply due to the fact maps internally have intricate implementation which might move values they contain in memory to provide (amortized) fast access time when the map's structure changes due to insertions and/or deletions of its elements.
The fact map values are not addressable means you can not do something like
m := make(map[int]string)
m[42] = "hello"
go mutate(&m[42]) // take a single element and go modifying it...
// ...while other parts of the program change _other_ values
m[123] = "blah blah"
The reason you are not allowed to do this is the insertion operation m[123] = ...
might trigger moving the storage of the map's element around, and that might involve moving the storage of the element keyed by 42
to some other place in memory — pulling the rug from under the feet of the goroutine running the mutate
function.
So, in Go, maps really only support three operations:
You cannot modify an element "in place" — you can only go in three steps:
As you can now see, the steps (1) and (3) are mere map accesses, and so the answer to your question is (hopefully) apparent: the step (1) shall be done under at least an read lock, and the step (3) shall be done under a write (exclusive) lock.
In contrast, elements of other compound types — arrays (and slices) and fields of struct
types — do not have the restriction maps have: provided the storage of the "enclosing" variable is not relocated, it is fine to change its different elements concurrently by different goroutines.
Since the only way to change the value associated with the key in the map is to reassign the changed value to the same key, that is a write / modification, so you have to obtain the write lock–simply using the read lock will not be sufficient.