Junior — Middle
Is it possible to ensure safety when reading data from a Map in a multithreaded environment?
sobes.tech AI
Answer from AI
In Go, a standard map is not thread-safe for concurrent access. If multiple goroutines read from a map without writing, it is safe. However, if at least one goroutine writes to the map, concurrent reading and writing will cause a panic.
To safely read from a map concurrently without writing, you can use a regular map without synchronization. But if there is a possibility of writing, you need to use synchronization, for example, via sync.RWMutex or by using sync.Map, which is specifically designed for concurrent access.
Example with sync.RWMutex for safe reading and writing:
var (
m = make(map[string]int)
mu sync.RWMutex
)
// Writing
func write(key string, value int) {
mu.Lock()
defer mu.Unlock()
m[key] = value
}
// Reading
func read(key string) (int, bool) {
mu.RLock()
defer mu.RUnlock()
val, ok := m[key]
return val, ok
}
If you guarantee that the map does not change after initialization, then concurrent reading is safe without additional synchronization.