Read-write safety over routines

Hello everyone

I have made a function that reads some data that can be heavy to calculate over and over again. So the function caches the data in a map on the first read and then just returns the values from the map.

Is it save to access this function from multiple go routines?

Hi @Michael_Hugi,

Reading a map is fine across goroutines. For writing, you need to use synchronization mechanisms because maps are not thread-safe.

Possible options for ensuring that write operations to a map are thread-safe include:

  • use sync.RWMutex as in this SO answer. TL;DR: Read operations use RLock() to block writers but not other readers. Write operations use Lock() to block all others.
  • use sync.Map but be aware that you lose compile-time type safety because of interface{} usage. (Generics in 1.18 (or later) will address this drawback.)
1 Like