Sobes.tech
Middle+

Is the map thread-safe in Go?

sobes.tech AI

Answer from AI

In Go, the built-in map type is not thread-safe for concurrent read and write operations from multiple goroutines. If multiple goroutines read and write to a map simultaneously without synchronization, it will cause a runtime panic.

To safely use a map in a concurrent environment, synchronization mechanisms such as a mutex from the sync package should be used:

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

// Writing
mu.Lock()
m["key"] = 42
mu.Unlock()

// Reading
mu.Lock()
value := m["key"]
mu.Unlock()

Alternatively, sync.Map can be used, which implements a thread-safe map with optimizations for certain scenarios.

Is the map thread-safe in Go? — Golang - sobes.tech