Senior
Kas on võimalik kirjutada ühte kaarti korraga erinevatest gorutinidest? Mis juhtub?
sobes.tech AI
Vastus AI-lt
In Go, it is not safe to write to the same map from different 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 and 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 unexpectedly crash.