Sobes.tech
Junior — Middle

What will happen if multiple goroutines try to access the same key in a map simultaneously?

sobes.tech AI

Answer from AI

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

To avoid this, synchronization mechanisms should be used:

  • 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]
}
What will happen if multiple goroutines try to access… - sobes.tech