Sobes.tech
Junior — Middle

Mis juhtub, kui mitu gorutinit üheaegselt püüavad pääseda sama võtme juurde kaardil?

sobes.tech AI

Vastus AI-lt

In Go, a map is not a thread-safe data structure. If multiple goroutines attempt to read and/or write to the same map simultaneously without synchronization, it will lead to race conditions and likely a runtime panic.

To prevent this, synchronization mechanisms such as:

  • sync.Mutex to lock access to the map.
  • sync.RWMutex to separate read and write locks.
  • Specialized structures like sync.Map which are safe for concurrent access.

Example of using sync.Mutex to protect a map:

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

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

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