Skip to content

Lesson 5 of 13 · 20m

Shared Memory: Mutexes, Atomics, and the Races That Ship

concurrent map writes is a fatal error recover() can't catch — mutexes, RWMutex costs, typed atomics, and what -race actually proves.

The crash log said fatal error: concurrent map read and map write and the process was gone. Not a panic — recover() cannot touch a runtime fatal error. It prints the stacks and kills the binary, mid-request, mid-anything. The wrong mental model is "channels for everything" — the proverb says share memory by communicating, but a real service still shares memory, and it has to do it on purpose.

When a mutex beats a channel

Channels move data between goroutines. A mutex protects state several goroutines touch — a cache, a stats counter, a config snapshot. Forcing that state through a channel adds a broker goroutine and a serialization point where a lock is three lines:

type Stats struct {
	mu   sync.RWMutex
	hits map[string]int64
}

func (s *Stats) Inc(k string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.hits[k]++
}

func (s *Stats) Get(k string) int64 {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.hits[k]
}

Rules that keep you alive: the lock guards specific fields — name it mu, keep it unexported, park it next to what it protects; never take locks in an order two paths disagree on; keep the critical section to data, not I/O. defer mu.Unlock() in a hot loop costs a defer per iteration — unlock explicitly when the profile says so.

RWMutex allows many concurrent readers — and each RLock/RUnlock is slower than a plain Lock because it updates a shared reader count. It earns its keep only when reads vastly outnumber writes and critical sections aren't trivial. Under heavy write pressure it buys nothing. Profile, don't assume.

Atomics for scalars

Since Go 1.19, atomic.Int64, atomic.Bool, atomic.Uint64 give race-free scalars without a lock:

var inFlight atomic.Int64
inFlight.Add(1)
defer inFlight.Add(-1)

Atomics are for counters, flags, and last-value-wins snapshots. The moment the logic is "check this AND update that," you wanted a mutex — atomics compose into subtle races faster than they compose into correctness. sync.OnceValue(f) (Go 1.21) memoizes a lazy computation; sync.Once guards init exactly once and is the right answer to "initialize on first use."

sync.Map exists for two narrow cases — write-once-read-many caches and key sets disjoint per goroutine — and underperforms map + RWMutex almost everywhere else. Reach for it last, not first.

What the race detector actually does

go test -race instruments memory accesses and tracks happens-before at runtime. It finds races the code actually executes — a race on a path your tests don't run is a race you'll ship. The cost is real (the docs put it at roughly 5–10× memory and up to 20× CPU), which is why it lives in CI and canary tests, not your dev default. A found race is a logic bug even if production never glitches on it — the Go memory model gives a racy program no guarantees, not degraded ones. That map write didn't just corrupt a count; it ended the process.

go vet's copylocks check catches the cousin bug: copying a struct containing a sync.Mutex — passing Stats by value, for _, s := range servers over mutex-bearing structs. A copied mutex protects a copy of nothing.

Field notes

  • sync.Pool amortizes allocation on hot paths (buffers, decoders); the GC may empty it at any collection. It is not a cache, and cleared entries aren't a bug.
  • concurrent map iteration and map write is the same fatal class: maps tolerate zero writers-plus-readers without synchronization, full stop.
  • Uber's style guide (github.com/uber-go/guide) carries the canonical production treatment of this in team-playbook form.

Try this

Write a map[string]int incremented by 100 goroutines, no lock. Run it under -race and read the report — two stacks, both accesses named. Then run it uninstrumented in a loop until fatal error: concurrent map writes kills the process. Now fix it with atomic.Int64 and again with sync.Mutex, and benchmark both — the result will surprise nobody who has profiled it before.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.