Junior — Middle
Millised olukorrad võivad tekkida samaaegse kirjutamise ajal kaarditüüpi salvestusse?
sobes.tech AI
Vastus AI-lt
In Go, the standard map (map) is not safe for concurrent read and write operations from multiple goroutines. If multiple goroutines write data to the map simultaneously without synchronization, it can lead to a runtime panic with the message "concurrent map writes" or unpredictable behavior of the program.
To avoid such problems, synchronization mechanisms such as mutex (sync.Mutex) or specialized structures like sync.Map should be used; these are safe for concurrent access.
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 unexpected program termination.