Mutexes in Go
Guarding shared state that goroutines both touch.
type Counter struct {
mu sync.Mutex
counts map[string]int
}
func (c *Counter) Add(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.counts[key]++
}
func (c *Counter) Get(key string) int {
c.mu.Lock()
defer c.mu.Unlock()
return c.counts[key]
}
How it works
sync.Mutexembedded in the struct guards its map.Lockwithdefer Unlockis the safe pattern.- Both read and write paths take the lock.
Keywords and builtins used here
deferfuncintmapreturnstringstructtype
The run, in numbers
- Lines
- 16
- Characters to type
- 246
- Tokens
- 86
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 49 seconds.
Step 1 of 5 in Synchronization, step 14 of 25 in Concurrency.