typestar

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

  1. sync.Mutex embedded in the struct guards its map.
  2. Lock with defer Unlock is the safe pattern.
  3. Both read and write paths take the lock.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 5 in Synchronization, step 14 of 25 in Concurrency.

← Previous Next →

Mutexes in other languages