源码索引 / CURRENT IMPLEMENTATION
learning/go-patterns/patterns/shared-map/shared_map.go
53 行 · 点击行号可定位;函数链接随声明位置更新,不手填行号。
跳到函数 / 声明
// Package sharedmap demonstrates protecting a map behind a mutex and returning
// snapshots instead of exposing shared mutable state.
package sharedmap
import "sync"
// Store is safe for concurrent use. Do not copy a Store after first use.
type Store struct {
mu sync.RWMutex
values map[string]int
}
// NewStore creates an initialized Store.
func NewStore() *Store {
return &Store{values: make(map[string]int)}
}
// Set associates value with key.
func (s *Store) Set(key string, value int) {
s.mu.Lock()
defer s.mu.Unlock()
if s.values == nil {
s.values = make(map[string]int)
}
s.values[key] = value
}
// Get returns the value for key, if present.
func (s *Store) Get(key string) (int, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
value, ok := s.values[key]
return value, ok
}
// Len returns the number of stored keys.
func (s *Store) Len() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.values)
}
// Snapshot returns a copy that the caller may mutate independently.
func (s *Store) Snapshot() map[string]int {
s.mu.RLock()
defer s.mu.RUnlock()
snapshot := make(map[string]int, len(s.values))
for key, value := range s.values {
snapshot[key] = value
}
return snapshot
}