Junior — Middle
What are the possible consequences if multiple threads modify a map data structure simultaneously?
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 modify the 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 such as mutexes (sync.Mutex) or specialized thread-safe data structures should be used, or the sync.Map package, which implements a thread-safe map.
Example using a mutex:
var (
m = make(map[string]int)
mu sync.Mutex
)
func write(key string, value int) {
mu.Lock()
defer mu.Unlock()
m[key] = value
}
func read(key string) int {
mu.Lock()
defer mu.Unlock()
return m[key]
}
Without such synchronization, the program may crash or get corrupted data.