State Management with Mutex

State Management with Mutex in Go: Channels move data between goroutines. Sometimes there is nothing to move -- there is one map, one counter, one config…

The Analogy: The Reading Room and the One Key

Channels move data between goroutines. Sometimes there is nothing to move -- there is one map, one counter, one config struct, and forty goroutines that all need to touch it in place. For that you want the one key to the reading room: whoever holds it may enter and rearrange the shelves, and everyone else waits at the door. mu.Lock() is taking the key; mu.Unlock() is hanging it back on the hook. There is exactly one key, so there is exactly one goroutine inside.

A sync.RWMutex is the same reading room with a more generous rule for readers. Any number of people may sit and read the ledger at once, because reading changes nothing. But the moment the archivist needs to rewrite a page, everybody is asked to leave and nobody new is let in until the rewrite is finished. RLock/RUnlock for readers, Lock/Unlock for the one writer -- and the two are mutually exclusive, not merely polite about it.

The critical thing the key does not do is know what it protects. A mutex guards data, not code, and nothing in the language connects one to the other. That connection lives entirely in a comment and in your discipline, which is why idiomatic Go puts the mutex immediately above the fields it guards with a // guards ... note, and why guarded fields are unexported. One method that touches the map without taking the key is enough to reintroduce the race that the other twenty methods were preventing.

Where the analogy stops: this key cannot be borrowed twice. A mutex is not reentrant -- if a goroutine holding the lock calls something that locks again, it waits for itself forever, and the runtime cannot always tell you that is what happened. It also has no memory of who holds it, so any goroutine may unlock a mutex any other goroutine locked (that is what makes the "unlock in a different function" bug possible). And holding the key while you make a network call converts a shared resource into a queue.


Syntax or Core Structure

package main

import (
	"fmt"
	"sort"
	"sync"
)

type Counter struct {
	mu     sync.Mutex // guards counts and total
	counts map[string]int
	total  int
}

func NewCounter() *Counter {
	return &Counter{counts: make(map[string]int)}
}

func (c *Counter) Add(key string, n int) {
	c.mu.Lock()
	defer c.mu.Unlock() // survives panics and early returns
	c.counts[key] += n
	c.total += n
}

// Returns a copy. Never hand a caller a reference to guarded state.
func (c *Counter) Snapshot() (map[string]int, int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	out := make(map[string]int, len(c.counts))
	for k, v := range c.counts {
		out[k] = v
	}
	return out, c.total
}

func main() {
	c := NewCounter()

	var wg sync.WaitGroup
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			c.Add("hits", 1)
			c.Add("bytes", 10)
		}()
	}
	wg.Wait()

	counts, total := c.Snapshot()

	keys := make([]string, 0, len(counts))
	for k := range counts {
		keys = append(keys, k)
	}
	sort.Strings(keys) // map iteration order is randomised; sort to print
	for _, k := range keys {
		fmt.Printf("%-6s %d\n", k, counts[k])
	}
	fmt.Println("total:", total)

	// RWMutex: concurrent readers, exclusive writer. Zero value is ready.
	var mu sync.RWMutex
	config := map[string]string{"mode": "fast"}

	read := func(k string) string {
		mu.RLock()
		defer mu.RUnlock()
		return config[k]
	}
	write := func(k, v string) {
		mu.Lock()
		defer mu.Unlock()
		config[k] = v
	}

	write("mode", "safe")
	fmt.Println("mode:", read("mode"))
}

Output:

bytes  500
hits   50
total: 550
mode: safe

Fifty goroutines each performed two Add calls in an unknown order, and the totals are still exactly 50 and 500. That is the entire promise of a mutex: not ordering, just the guarantee that c.counts[key] += n and c.total += n happen together, with nobody looking.


Technical Depth: The sync Toolbox

Choosing the right primitive

PrimitiveUse it forNotes
sync.MutexAny invariant spanning more than one word, or a map/slice touched in placeZero value ready. The default choice.
sync.RWMutexRead-heavy state where readers hold the lock for a non-trivial timeTwo lock modes, more overhead per operation than Mutex.
sync/atomic (atomic.Int64, atomic.Bool, atomic.Pointer[T])One word, read and written independently of anything elseLock-free, no critical section. Typed wrappers since Go 1.19.
sync.OnceExactly-once lazy initialisationLets a zero-value struct be usable with no constructor.
sync.WaitGroupWaiting for a known set of goroutinesNot a lock; carries no data.
sync.MapA map with disjoint key sets per goroutine, or write-once/read-manySlower than map + Mutex for ordinary mixed workloads. Not the default.
sync.CondWaiting for a predicate over guarded state to become trueAlmost always better expressed with a channel.
sync.PoolRecycling large short-lived buffersContents can vanish at any GC. Never for anything you must keep.

The zero value works, and copies are fatal

var mu sync.Mutex is an unlocked, ready mutex -- there is no NewMutex. The flip side is that a Mutex must never be copied, because a copy is a second, independent lock. Passing a struct containing a mutex by value, or ranging over a slice of such structs by value, silently gives every copy its own key. Methods on such a type therefore take a pointer receiver, always. go vet's copylocks check catches most cases, and it is worth treating as an error.

It is not reentrant, and it has no owner

func (c *Counter) AddTwice(k string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.Add(k, 1) // Add locks again -> this goroutine waits for itself
}

That deadlocks. There is no owner recorded, so the runtime cannot say "you already hold this". The standard fix is the unexported inner method convention: Add locks and calls addLocked, and every method that already holds the lock calls addLocked instead. Name the lock-free versions with a Locked suffix so the requirement is visible at the call site.

RWMutex has a sharper version of the same trap: a goroutine that holds RLock and calls RLock again can deadlock if a writer arrived in between, because a pending writer blocks new readers. Recursive read locking is not safe in Go.

What the lock actually costs

sync.Mutex has a fast path that is a single atomic compare-and-swap when uncontended -- tens of nanoseconds, no system call. Under contention it spins briefly, then parks the goroutine with the runtime. Since Go 1.9 it has a starvation mode: a waiter that has been queued for more than 1 ms flips the mutex into handoff mode so it is granted the lock directly, which bounds the unfairness. So a mutex is not FIFO, but nobody waits unboundedly.

RWMutex is not free for readers -- RLock is also an atomic operation, and on a many-core machine the shared reader counter becomes a cache-line contention point. For very short critical sections (reading one map key) a plain Mutex frequently beats RWMutex. Reach for RWMutex when readers greatly outnumber writers and each read holds the lock long enough to matter. Measure it (Module 11) rather than assuming.

Atomics for single words, and copy-on-write for read-mostly state

Independent counters do not belong inside the critical section at all:

var requests atomic.Int64
requests.Add(1)        // no lock, no critical section
n := requests.Load()

And for configuration that is read constantly and replaced rarely, swap a whole immutable value instead of guarding a mutable one:

var cfg atomic.Pointer[Config]
cfg.Store(&Config{Mode: "safe"}) // writers build a new one
c := cfg.Load()                  // readers never block, never lock

Readers get a consistent snapshot with no lock at all; writers pay the cost of building a fresh Config. This is the right shape for feature flags, routing tables and parsed templates.

sync.Once and friends

once.Do(f) runs f exactly once across all goroutines, and every caller blocks until that first run finishes -- so a slow initialiser is safe, not merely deduplicated. If f panics, the Once is still considered done. Go 1.21 added sync.OnceFunc, OnceValue and OnceValues, which wrap the pattern:

var loadRules = sync.OnceValue(func() []Rule { return parseRules() })
// every call site just writes loadRules()

Avoiding deadlock

  • Keep critical sections tiny. Compute outside, mutate inside.
  • Never call unknown code while holding a lock -- no callbacks, no interface methods you do not own, no channel operations, no I/O. That is how a lock ends up held across a 30-second timeout.
  • Acquire multiple locks in a single global order and document it. Two goroutines taking a then b and b then a is the classic deadlock.
  • One mutex per invariant, not one per struct field and not one for the whole program.
  • Unlock on an already-unlocked mutex is fatal error: sync: unlock of unlocked mutex -- unrecoverable, not a panic you can catch.
  • Run everything under -race. It reports missing locks; it cannot report locks you took in the wrong order.

Real World Example: A Scoreboard With Three Different Guards

One type, three synchronisation strategies, each chosen for what it protects: an RWMutex over the map, atomics over the independent counters, and a Once so the zero value is usable without a constructor.

package main

import (
	"fmt"
	"sort"
	"sync"
	"sync/atomic"
)

type Board struct {
	once sync.Once

	mu     sync.RWMutex // guards scores
	scores map[string]int

	// Independent single words: not part of the scores invariant,
	// so they are deliberately outside mu.
	reads  atomic.Int64
	writes atomic.Int64
}

// Lazy init: makes var b Board legal with no NewBoard.
func (b *Board) init() {
	b.once.Do(func() {
		b.scores = map[string]int{"ada": 0, "grace": 0, "alan": 0}
	})
}

func (b *Board) Add(name string, pts int) {
	b.init()
	b.writes.Add(1) // outside the lock: shortest possible critical section
	b.mu.Lock()
	defer b.mu.Unlock()
	b.scores[name] += pts
}

func (b *Board) Score(name string) int {
	b.init()
	b.reads.Add(1)
	b.mu.RLock()
	defer b.mu.RUnlock()
	return b.scores[name]
}

// Copy under the read lock, then format and sort outside it.
func (b *Board) Snapshot() []string {
	b.init()
	b.mu.RLock()
	lines := make([]string, 0, len(b.scores))
	for n, s := range b.scores {
		lines = append(lines, fmt.Sprintf("%-6s %3d", n, s))
	}
	b.mu.RUnlock() // released before the sort: locks are not for CPU work
	sort.Strings(lines)
	return lines
}

func main() {
	var b Board // no constructor needed
	names := []string{"ada", "grace", "alan"}

	var wg sync.WaitGroup
	for w := 0; w < 6; w++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for r := 0; r < 10; r++ {
				name := names[r%len(names)]
				b.Add(name, 1)
				_ = b.Score(name)
			}
		}()
	}
	wg.Wait()

	for _, line := range b.Snapshot() {
		fmt.Println(line)
	}
	fmt.Println("writes:", b.writes.Load())
	fmt.Println("reads:", b.reads.Load())
}

Output:

ada     24
alan    18
grace   18
writes: 60
reads: 60

Every number here is forced, not observed. Each of the six goroutines runs ten rounds, and r % 3 over r = 0..9 picks ada four times and the other two three times each -- so ada must end on 24 and the others on 18, with 60 writes and 60 reads. Sixty goroutine-interleavings later the arithmetic is still exact, which is the only claim a mutex makes. It says nothing about order: which goroutine incremented ada to 17 is unknowable and irrelevant.

The three guards protect three different things, and mixing them up is the usual design error. scores is a map read and written in place, so it needs mu. reads and writes are single words that nobody correlates with the map, so they are atomics -- putting them inside mu would lengthen every critical section for no invariant. And scores needing to exist before first use is a one-time problem, which is Once. Ask "what invariant am I protecting, and how wide is it?" and the primitive follows.

Snapshot releases the lock before it sorts, and that is deliberate. Formatting three strings and sorting them is pure CPU work over data nobody else can see any more, so doing it under RLock would block writers for no reason. The general rule reads: copy what you need under the lock, then do everything else outside it. The same rule is why Snapshot returns []string rather than the map -- handing a caller the guarded map would let them read it, unlocked, while another goroutine writes it, and the race detector would blame a line inside Board for a bug in the caller.

var b Board works because of Once, and this is a real API decision. A type whose zero value is usable needs no constructor, cannot be constructed wrongly, and can be embedded in another struct with no initialisation ceremony -- the same property sync.Mutex, bytes.Buffer and strings.Builder all have. The cost is an init() call at the top of every exported method and a Once field to carry around. When the type genuinely needs arguments, use a constructor instead; when its zero value is meaningful, this pattern is worth the two extra lines.


Common Mistakes

  1. Copying a struct that contains a Mutex. Every copy gets its own lock, so nothing is actually protected. Use pointer receivers and pointer parameters; enable go vet's copylocks.
  2. Forgetting defer mu.Unlock(). Any early return, continue or panic then leaves the lock held forever, and the next Lock hangs with no message.
  3. Locking recursively. A method that holds the lock and calls another method that takes it deadlocks against itself. Split into Foo (locks) and fooLocked (assumes locked).
  4. Returning guarded state by reference. Returning the map, a slice into it, or a pointer to a guarded field lets the caller read it without the lock. Return copies.
  5. Holding a lock across I/O, a channel operation or a callback. One slow network call turns a shared counter into a global queue, and a callback that locks again deadlocks.
  6. Guarding independent counters with the shared mutex. It works, but it serialises everything on an invariant that does not exist. Use atomic.Int64.
  7. Reaching for RWMutex by default. Its per-operation cost is higher and its reader counter contends across cores; for short critical sections Mutex is usually faster. Benchmark before switching.
  8. Read-locking, then upgrading to a write lock. There is no upgrade in Go, and RLock followed by Lock in the same goroutine deadlocks. Take Lock from the start, then re-check the condition inside it.
  9. Assuming sync.Map is "the concurrent map". It is tuned for disjoint keys and write-once workloads; for ordinary mixed read/write traffic map plus Mutex is simpler and often faster.
  10. Taking two locks in inconsistent order. a then b in one function and b then a in another is a deadlock waiting for load. Document one global order and never deviate.
  11. Believing a clean -race run proves correctness. The detector finds unsynchronised access, not lock-ordering deadlocks, not lost wakeups, and not races on paths your test never executed.

Best Practices

  • Put the mutex directly above the fields it guards, with a // guards ... comment, and keep those fields unexported.
  • Give the type pointer-receiver methods and let those methods be the only thing that touches guarded state.
  • Lock then defer Unlock on the next line, every time -- the pair should be readable in one glance.
  • Compute outside, mutate inside: the critical section holds assignments, not formatting, sorting or I/O.
  • Return copies or derived values from accessors; never a handle to guarded memory.
  • Use atomic types for standalone counters and flags, and atomic.Pointer copy-on-write for read-mostly configuration.
  • Use sync.Once (or OnceValue) when you want a usable zero value instead of a constructor.
  • Prefer splitting state over guarding it, and a channel over a lock when you are transferring ownership rather than sharing it.

Practice Exercises

  1. Change Add, Score and Snapshot to value receivers (func (b Board)) and record exactly what go vet reports and what the program prints. Explain the printed numbers in terms of how many mutexes now exist.
  2. Move b.writes.Add(1) inside the critical section and replace atomic.Int64 with a plain int64. Confirm the program still prints 60, then explain why the atomic version was preferable anyway.
  3. Add a method AddAll(names []string, pts int) that takes the write lock once and updates several names, without deadlocking against Add. Name the helper you extract and say why the suffix matters.
  4. Replace the RWMutex and scores map with an atomic.Pointer to an immutable map[string]int that writers replace by copying. Get the same output, then describe which workload each of the two designs is better for.