Intern
Is het veilig om kaarten gelijktijdig te lezen in Go?
sobes.tech AI
Antwoord van AI
In Go is het lezen uit een map niet thread-safe als er tegelijkertijd wordt geschreven. Om veilig te lezen in een multithread-omgeving, moet synchronisatie worden gebruikt, bijvoorbeeld sync.RWMutex voor lezen en schrijven, of sync.Map, dat speciaal is ontworpen voor gelijktijdige toegang.
Voorbeeld met sync.RWMutex:
import (
"sync"
)
var (
m = make(map[string]int)
mu sync.RWMutex
)
func read(key string) (int, bool) {
mu.RLock() // lees-lock
defer mu.RUnlock() // unlock
val, ok := m[key]
return val, ok
}
func write(key string, val int) {
mu.Lock() // schrijf-lock
defer mu.Unlock() // unlock
m[key] = val
}
Of gebruik sync.Map:
import "sync"
var m sync.Map
func read(key string) (interface{}, bool) {
return m.Load(key)
}
func write(key string, val interface{}) {
m.Store(key, val)
}
sync.Map is handig wanneer er veel gelijktijdige operaties zijn, maar heeft specifieke kenmerken qua prestaties en API.