Sobes.tech
Senior

Goroutines write data to a shared map without synchronization — why is this bad and how can it be fixed?

sobes.tech AI

Answer from AI

In Go, maps are not thread-safe for concurrent writes from multiple goroutines. If multiple goroutines write to a map without synchronization, it leads to data races, panics, and unpredictable program behavior.

To fix this issue, access to the map must be synchronized. The main methods are:

  1. Using a mutex (sync.Mutex or sync.RWMutex) to lock the map during read and write operations:
var mu sync.Mutex
var m = make(map[string]int)

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

func read(key string) int {
    mu.Lock()
    defer mu.Unlock()
    return m[key]
}
  1. Using sync.Map — a thread-safe map implementation from the standard library, optimized for scenarios with many reads and fewer writes:
var m sync.Map

func write(key string, value int) {
    m.Store(key, value)
}

func read(key string) (int, bool) {
    v, ok := m.Load(key)
    if !ok {
        return 0, false
    }
    return v.(int), true
}

Thus, synchronization prevents data races and ensures correct program operation.

Goroutines write data to a shared map without… - sobes.tech