Junior — Middle
Mis juhtub, kui mitu gorutinit üheaegselt püüavad pääseda sama võtme juurde kaardil?
sobes.tech AI
Vastus AI-lt
In Go, a map is not a thread-safe data structure. If multiple goroutines attempt to read and/or write to the same map simultaneously without synchronization, it will lead to race conditions and likely a runtime panic.
To prevent this, synchronization mechanisms such as:
sync.Mutexto lock access to the map.sync.RWMutexto separate read and write locks.- Specialized structures like
sync.Mapwhich are safe for concurrent access.
Example of using sync.Mutex to protect a map:
var mu sync.Mutex
var m = make(map[string]int)
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]
}