Middle — Middle+
Kuidas tagada turvaline töö Map kogumikuga mitme niidiga keskkonnas?
sobes.tech AI
Vastus AI-lt
In Go, the standard map (map) is not safe for concurrent read and write from different goroutines. To ensure safe operation of the map in a multithreaded environment, the following approaches can be used:
- Synchronization using mutex
Use sync.Mutex or sync.RWMutex to protect access to the map. Lock the mutex for writing during write operations, and for reading during read operations (if using RWMutex).
import "sync"
type SafeMap struct {
mu sync.RWMutex
m map[string]int
}
func (s *SafeMap) Get(key string) (int, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
val, ok := s.m[key]
return val, ok
}
func (s *SafeMap) Set(key string, val int) {
s.mu.Lock()
defer s.mu.Unlock()
s.m[key] = val
}
- Using
sync.Map
Go has a specialized sync.Map structure, optimized for concurrent access and does not require manual synchronization.
import "sync"
var m sync.Map
// Write
m.Store("key", 42)
// Read
val, ok := m.Load("key")
- Using channels
Access to the map can be organized through a goroutine that handles read and write requests via channels, ensuring sequential access.
The choice of method depends on specific performance requirements and implementation complexity.