Write a goroutine-safe counter with Inc per key and Snapshot
Implement Counter, used by many goroutines at the same time. Inc(key) adds one to the count of key; Snapshot() returns a map with the current count of every key. The zero value var c Counter must work. Requirements: the counts are exact when 100 goroutines call Inc at once; the map from Snapshot is a copy, so later Inc calls do not change it and changing it does not change the counter. The browser run cannot show a data race; the cloud check runs the tests with go test -race.
type Counter struct {
// your fields
}
func (c *Counter) Inc(key string) {
// your code here
}
func (c *Counter) Snapshot() map[string]int {
// your code here
}Write the implementation.
Do not add extra imports unless the task says so explicitly.
Guard a map[string]int with a sync.Mutex: Inc locks, creates the map if it is nil, increments the key and unlocks. Snapshot locks, copies every entry into a fresh map and returns it, so callers never touch the shared map.
- Locking in
Incbut returning the internal map fromSnapshot, so callers race with the writers - Forgetting to create the map, so the zero value panics on assignment to a nil map
- Copying a
Counterby value: the copy shares the map but locks its own mutex, so the map loses its protection
- When would
sync.RWMutexorsync.Mapbeat a plain mutex here? - How would you use
atomic.Int64if the set of keys were fixed in advance?
Solution
The shared state is a map; the mutex stands before every access to it, writes and reads alike. Snapshot must hand out a copy: returning the internal map lets a reference to data that other goroutines keep changing escape the lock. The map is created lazily inside Inc, so the zero value of Counter is ready to use. A Counter must not be copied by value: the mutex would be copied with it (go vet catches this).
type Counter struct {
mu sync.Mutex
m map[string]int
}
func (c *Counter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.m == nil {
c.m = make(map[string]int)
}
c.m[key]++
}
func (c *Counter) Snapshot() map[string]int {
c.mu.Lock()
defer c.mu.Unlock()
out := make(map[string]int, len(c.m))
for k, v := range c.m {
out[k] = v
}
return out
}Check such solutions with go test -race: it catches a missing lock, while a plain run does not.