Junior — Middle
Kaip sinchronizuoti prieigos prie bendro ištekliaus naudojant Map struktūrą ir Mutex mechanizmą?
sobes.tech AI
Atsakymas iš AI
Go kalboje, siekiant sinchronizuoti prieigą prie bendros Map struktūros, paprastai naudojamas mutexas (sync.Mutex), nes map nėra srautinė saugi.
Pavyzdys:
import (
"sync"
)
var (
mu sync.Mutex
sharedMap = make(map[string]int)
)
func writeToMap(key string, value int) {
mu.Lock() // užrakina prieigą
sharedMap[key] = value
mu.Unlock() // atrakina
}
func readFromMap(key string) (int, bool) {
mu.Lock()
val, ok := sharedMap[key]
mu.Unlock()
return val, ok
}
Šiuo būdu, prieš skaitant ar rašant į map, užrakiname mutex, kad išvengtume lenktynių sąlygų ir užtikrintume teisingą veikimą konkurencinėje aplinkoje.