Junior — Middle
What situations can arise when writing simultaneously to a map-type storage?
sobes.tech AI
Answer from AI
In Go, the standard map is not thread-safe for concurrent read and write operations from multiple goroutines. If multiple goroutines write to a map simultaneously without synchronization, it can lead to a runtime panic with the message "concurrent map writes" or unpredictable program behavior.
To avoid such issues, synchronization mechanisms like mutex (sync.Mutex) or specialized structures like sync.Map, which are safe for concurrent access, should be used.
Example with mutex:
var mu sync.Mutex
var m = make(map[string]int)
func writeToMap(key string, value int) {
mu.Lock()
defer mu.Unlock()
m[key] = value
}
Without such protection, concurrent writes can lead to data corruption or program crashes.