Intern
Kas on turvaline kaarte lugeda Go-s?
sobes.tech AI
Vastus AI-lt
In Go, reading from a map is not thread-safe if a write occurs simultaneously. To safely read in a multithreaded environment, synchronization must be used, such as 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() // read lock
defer mu.RUnlock() // unlock
val, ok := m[key]
return val, ok
}
func write(key string, val int) {
mu.Lock() // write lock
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 useful when there are many concurrent operations, but it has specific characteristics regarding performance and API.