Sobes.tech
Junior — Middle

Kuidas käitub programm, kui samaaegselt toimub konkurentsivõimeline väärtuste lugemine kaardilt?

sobes.tech AI

Vastus AI-lt

In Go, concurrent safe reading from a map does not cause panic or errors. Problems occur if there is simultaneous writing or reading and writing. If only a few goroutines read values from the map without modifying them, it is safe. But if at least one goroutine modifies the map, synchronization mechanisms like sync.RWMutex or sync.Map are necessary.

Example of safe reading using sync.RWMutex:

var m = make(map[string]int)
var mu sync.RWMutex

func read(key string) int {
    mu.RLock()
    defer mu.RUnlock()
    return m[key]
}

func write(key string, value int) {
    mu.Lock()
    defer mu.Unlock()
    m[key] = value
}

Thus, concurrent reading without writing is safe, but when writing, synchronization is required.