Senior
If a map is initialized once at startup and used only for reading, is synchronization needed?
sobes.tech AI
Answer from AI
If a map is initialized once at the start of a program and then only used for reading, synchronization is not necessary. In Go, reading from a map is safe for concurrent access if no one is writing to it at the same time. The main thing is to ensure that the write (initialization) is completed before starting parallel reads.
Example:
var m map[string]int
func initMap() {
m = map[string]int{"a": 1, "b": 2}
}
func readMap(key string) int {
return m[key]
}
func main() {
initMap() // initialization before starting goroutines
// now it's safe to read from m in multiple goroutines without mutexes
}