Sobes.tech
Junior — Middle

Is it safe to use shared resources like Map when accessed concurrently from multiple goroutines?

sobes.tech AI

Answer from AI

No, the standard map in Go is not thread-safe and cannot be used concurrently from multiple goroutines without additional synchronization. Concurrent access without protection can lead to data races and panics.

To safely use shared resources like maps in a multithreaded environment, you can:

  • Use sync.Mutex or sync.RWMutex to protect access to the map.
  • Use sync.Map — a specialized thread-safe data structure for maps.

Example with mutex:

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]
}

Using sync.Map:

var m sync.Map

m.Store("key", 42)
value, ok := m.Load("key")