Sobes.tech
Junior — Middle

What are the consequences of concurrent writing to a Map from different competing goroutines?

sobes.tech AI

Answer from AI

In Go, the standard map is not thread-safe for concurrent read and write operations from multiple goroutines. If multiple goroutines try to write to the same map simultaneously without synchronization, it will lead to data races, runtime panic (fatal error: concurrent map writes), and unpredictable program behavior.

To avoid issues, you should use:

  • Mutexes (sync.Mutex) to protect access to the map.
  • Specialized thread-safe data structures, such as sync.Map.

Example with a mutex:

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

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

Without such protection, the program may crash.

What are the consequences of concurrent writing to a… - sobes.tech