Intern
Is the map stream-safe in Go?
sobes.tech AI
Answer from AI
In Go, reading from a map is not thread-safe if a write occurs simultaneously. To safely read from a map in a multithreaded environment, synchronization is needed, for example, using sync.RWMutex for locking during read and write, or using sync.Map, which is specifically designed for concurrent access.
Example with sync.RWMutex:
import (
"sync"
)
var (
m = make(map[string]int)
mu sync.RWMutex
)
func read(key string) (int, bool) {
mu.RLock() // lock for reading
defer mu.RUnlock() // unlock
val, ok := m[key]
return val, ok
}
func write(key string, val int) {
mu.Lock() // lock for writing
defer mu.Unlock() // unlock
m[key] = val
}
Or use sync.Map:
import "sync"
var m sync.Map
func read(key string) (interface{}, bool) {
return m.Load(key)
}
func write(key string, val interface{}) {
m.Store(key, val)
}
sync.Map is convenient when there are many concurrent operations, but it has some performance and API considerations.