-2

Firstly, I have already read this How safe are Golang maps for concurrent Read/Write operations? and my question is not how safe golang maps are during read/write but a lot more specific. In multiple places in the above mentioned thread at SO, people have mentioned that Concurrent read from maps are still ok! and logically that should be the case but it turns out that there are some other resources as well where people mention golang maps are not even safe to read concurrently. For example take a look at the following resources

  1. https://go.dev/blog/maps
  2. https://www.youtube.com/watch?v=BywIJqYodl4

In one place https://groups.google.com/g/golang-nuts/c/_XHqFejikBg I saw people mentioned that reads are concurrent if it happens only after the initialisation of Maps. How sync.Map is playing here? Why reads are not concurrent if each goroutines process for a single key but writes happens after the map is initialised via other goroutines? It shouldn't be the case because for each key hash is being calculated and for a given hash write/read never happens by any other goroutines.

Please help to explain it. Thanks

Mayukh Sarkar
  • 2,289
  • 1
  • 14
  • 38

1 Answers1

0

If you create an initialize a map, and then create goroutines and read from it concurrently, it is safe, there is no need to serialize access. The initialization of the map must be completed before the goroutines start reading from it. There is a nuance here though: the map initialization must be complete before concurrent reads. If you complete the initialization before you create the goroutines, then it is safe. If you create the goroutines before map initialization is complete, then you have to make sure goroutines wait until initialization is complete by using a synchronization mechanism like a channel.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59