Junior — Middle
How does a program behave if concurrent reading of values from a map occurs simultaneously?
sobes.tech AI
Answer from AI
In Go, concurrent safe reading from a map is safe and does not lead to panics or errors. Problems occur if there is simultaneous reading and writing. When reading and writing to a map without synchronization, the program may cause a runtime panic with the message "concurrent map read and map write".
If only a few goroutines read values from the map without modifications, it is safe. But if at least one goroutine modifies the map, synchronization mechanisms such as sync.RWMutex or sync.Map should be used.
Example of safe reading using sync.RWMutex:
var m = make(map[string]int)
var mu sync.RWMutex
func read(key string) int {
mu.RLock()
defer mu.RUnlock()
return m[key]
}
func write(key string, value int) {
mu.Lock()
defer mu.Unlock()
m[key] = value
}
Thus, concurrent reading without writing is safe, but when writing, synchronization is necessary.