Junior — Middle
Come garantire un accesso sicuro alla carta in un ambiente multithread?
sobes.tech AI
Risposta dell'AI
In Go, per accedere in modo sicuro a una mappa (map) in un ambiente multithread, è necessario utilizzare la sincronizzazione, poiché map non è una struttura dati sicura per i thread. Il metodo più comune è usare un mutex (sync.Mutex o sync.RWMutex) per bloccare l'accesso durante la lettura e la scrittura.
Esempio con sync.RWMutex:
import (
"sync"
)
var (
m = make(map[string]int)
mu sync.RWMutex
)
func read(key string) int {
mu.RLock() // blocca per la lettura
defer mu.RUnlock()
return m[key]
}
func write(key string, value int) {
mu.Lock() // blocca per la scrittura
defer mu.Unlock()
m[key] = value
}
In Go esiste anche il tipo sync.Map, che implementa una mappa sicura per i thread con ottimizzazioni per operazioni di lettura frequenti. Può essere usato se non è richiesta una tipizzazione rigorosa e si desidera semplicità:
import "sync"
var m sync.Map
m.Store("key", 42) // scrittura
value, ok := m.Load("key") // lettura
Pertanto, per un accesso sicuro a una mappa in un ambiente multithread, usare mutex o sync.Map.