Senior
Is it possible to write to the same map from different goroutines simultaneously? What will happen?
sobes.tech AI
Answer from AI
In Go, it is not safe to write to a single map from multiple goroutines simultaneously without additional synchronization. The standard map is not thread-safe, and concurrent write operations can lead to a panic (runtime panic) or data corruption.
To safely use a map in a concurrent environment, you can:
- Use sync.Mutex or sync.RWMutex to protect access to the map.
- Use sync.Map — a specialized thread-safe data structure for maps.
Example with mutex:
var (
m = make(map[string]int)
mu sync.Mutex
)
func write(key string, value int) {
mu.Lock()
m[key] = value
mu.Unlock()
}
Without such protection, the program may crash.