Una forma agradable e idiomática de usar un mapa compartido.
Digamos que tenía un programa con acceso simultáneo a un mapa, como este:
func getKey(r *http.Request) string { ... }
values := make(map[string]int)
http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
key := getKey(r)
fmt.Fprint(w, values[key])
})
http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
key := getKey(r)
values[key] = rand.Int()
})
Esto es malo ya que las escrituras de mapas no son atómicas. Asiquepodría usar un mutex de lectura / escritura
func getKey(r *http.Request) string { ... }
values := make(map[string]int)
var lock sync.RWMutex
http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
key := getKey(r)
lock.RLock()
fmt.Fprint(w, values[key])
lock.RUnlock()
})
http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
key := getKey(r)
lock.Lock()
values[key] = rand.Int()
lock.Unlock()
})
Lo que parece estar bien, excepto por el hecho de que estamos usando mutexes directamente y no canales.
¿Cuál es una forma más idiomática de implementar esto? ¿O es este uno de esos momentos en que un mutex es realmente todo lo que necesitas?