Sobes.tech
Junior — Middle

Is it possible to ensure safety when writing to a Map from multiple threads simultaneously?

sobes.tech AI

Answer from AI

In Go, the standard map is not thread-safe for concurrent writes from multiple goroutines. If multiple goroutines write to a map simultaneously without synchronization, it will cause a panic.

To ensure safety during concurrent writes, you can:

  • Use a mutex (sync.Mutex or sync.RWMutex) to protect access to the map.
  • Use specialized thread-safe data structures, such as sync.Map, which is designed for concurrent access.

Example with a mutex:

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

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

Or use sync.Map:

var m sync.Map

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

Thus, to ensure safety during concurrent writes, synchronization must be used.

Is it possible to ensure safety when writing to a Map… - sobes.tech