typestar

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

  1. RLock may be held concurrently; Lock excludes everyone.
  2. Always unlock with defer, so a return cannot skip it.
  3. Embedding the mutex in the struct keeps them together.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 5 in Synchronization, step 15 of 25 in Concurrency.

← Previous Next →