Lesson 7 of 9 · 25m
Mutexes, Atomics, and sync.Once Without Superstition
Choose the narrowest synchronization primitive that matches the invariant and learn where mutexes, atomics, Once, and condition variables actually fit.
The race that hurts is rarely the one in your toy benchmark. It is a request handler reading a map while cleanup writes to it, a metrics cache mutated by two tenants, or a nil check that was correct half a nanosecond before the pointer changed. Synchronization exists to protect invariants, not to make the race detector quiet.
Protect the invariant
Ask what must remain true. If count and items must agree, locking only one is decorative:
c.mu.Lock()
defer c.mu.Unlock()
c.items[id]++
c.total += priceBoth mutations happen inside one critical section because the invariant is their relationship, not either field alone.
Keep critical sections small and boring
Do not perform network calls, disk writes, or arbitrary callbacks while holding a mutex unless the design truly requires it:
c.mu.Lock()
user := c.users[id]
c.mu.Unlock()
notify(user) // outside the critical sectionSmall critical sections make contention visible at the invariant. Giant locks serialize everything while still failing to explain what is protected.
Atomics are for tiny independent state
Use sync/atomic for counters, sequence numbers, and simple state transitions:
var inFlight atomic.Int64
inFlight.Add(1)
defer inFlight.Add(-1)Atomics do not compose. Two correct atomic operations do not protect the relationship between two variables. Multi-field invariants need a mutex or a channel-owned state machine.
Once is initialization, not retry
sync.Once runs exactly once:
var once sync.Once
var client *APIClient
func Client() *APIClient {
once.Do(func() { client = mustNewClient() })
return client
}If initialization can fail and should be retried, Once is wrong because failure still counts as done. Initialize during startup or implement mutex-protected error-aware initialization.
Field notes
- Copying a struct containing a mutex after use copies lock state incorrectly; pass pointers once initialized.
sync.RWMutexhelps only when reads dominate and critical sections are substantial; measure before using it.sync.Condis valid but rarely clearer than channels.- Lock ordering is architecture. If two locks can be held together, document and enforce their order.
Was this lesson helpful?