RWMutex in Go
Many readers or one writer, when reads dominate.
type Table struct {
mu sync.RWMutex
rows map[string]int
}
func NewTable() *Table {
return &Table{rows: make(map[string]int)}
}
func (t *Table) Set(key string, value int) {
t.mu.Lock()
defer t.mu.Unlock()
t.rows[key] = value
}
func (t *Table) Get(key string) (int, bool) {
t.mu.RLock()
defer t.mu.RUnlock()
value, ok := t.rows[key]
return value, ok
}
How it works
RLockmay be held concurrently;Lockexcludes everyone.- Always unlock with defer, so a return cannot skip it.
- Embedding the mutex in the struct keeps them together.
Keywords and builtins used here
booldeferfuncintmakemapreturnstringstructtype
The run, in numbers
- Lines
- 21
- Characters to type
- 354
- Tokens
- 124
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 71 seconds.
Step 2 of 5 in Synchronization, step 15 of 25 in Concurrency.