3 ms·
> As always, if one goroutine is writing to a map, no other goroutine should be reading or writing the map concurrently. What if you are writing to a value in
by smegel 11y ago
> As always, if one goroutine is writing to a map, no other goroutine should be reading or writing the map concurrently.
What if you are writing to a value in the map? Surely that is safe to do concurrently with other processes reading at least.
- jfolkins 11y ago>> As always, if one goroutine is writing to a map, no other goroutine should be reading or writing the map concurrently. > What if you are writing to a value in the map? Surely that is safe to do concurrently with other processes reading at least. Nope. You need to protect your state by communicating with channels or using a lock.
- smegel 11y ago> You need to protect your state by communicating with channels or using a lock. But what are you protecting? Setting a value will not cause a map rebalance, and so long as you are just setting a new value (not incrementing or like) it should be an atomic operation. Locking is really slow, and if you can find safe ways to avoid it, it can be a good thing.
- timtadh 11y agoAnother thread could 1) write to the same key. 2) cause a table expansion (or a shrink) which rehashes the whole table (in most implementations). Either case will cause a difficult to diagnose bug. Use a lock or communicate with channels instead. There may be other subtle things which can get corrupted under concurrent use. The map type in Go has never been implemented in a thread safe fashion so if you try and use it as such you will be in for a bad time.
- dsymonds 11y agoThere's nothing specified that setting a value won't cause a map rebalance or rehash. The implementation is allowed to change things under the hood.
- jaytaylor 11y agoLocks are actually really cheap in many instances; mutexes can Lock and Unlock millions of times per second as long as contention is low.
- tagrun 11y ago> so long as you are just setting a new value The hash map first needs to determine whether it already has a value with such a key or not, which requires some checking that typically involves many instructions and is not atomic. And to determine that, you at least need a read-lock.
- nemothekid 11y agoOnly if you do something like: ml.Lock() v := m["key"] // maybe m is something like map[string]*MyValue ml.Unlock() v.foo = "bar" // m["key"].foo is now bar, because m["key"] both point to the same object
- Strom 11y agoIf you ever intend to read that v.foo value in another goroutine, then that edit needs to be before freeing the lock as well.