Junior — Middle
What consequences can arise from concurrent writing to a map from multiple threads?
sobes.tech AI
Answer from AI
In Go, maps are not thread-safe for concurrent writes from multiple goroutines. If multiple threads try to write or modify data in the same map simultaneously without synchronization, it will lead to a runtime panic with the message "concurrent map writes".
To avoid this problem, synchronization mechanisms such as mutexes (sync.Mutex) or specialized data structures that ensure thread safety should be used. Alternatively, a channel can be used for sequential access to the map.
Example with a mutex:
var m = make(map[string]int)
var mu sync.Mutex
func write(key string, value int) {
mu.Lock()
m[key] = value
mu.Unlock()
}
Without such synchronization, the program may crash.