sync & atomic: WaitGroup, Mutex, RWMutex, Cond, Once, Pool, Atomic Counters
"If you must read the rest of this document to understand the behavior of your program, you are being too clever. Don't be clever." — The Go Memory Model, Advice
Summary: The sync and sync/atomic packages give goroutines that share memory a small set of tools: locks (Mutex, RWMutex), lifecycle helpers (WaitGroup, Once), a condition variable (Cond), an allocation cache (Pool), a concurrent map (sync.Map) and atomic values. Each one is defined by the happens-before edge it creates. Focus: Lock/Unlock and lock scope, TryLock, why Go mutexes are not reentrant, go vet copylocks, embedding a mutex versus a named field, contention and starvation mode, RLock/RUnlock and writer preference, WaitGroup.Add before go and WaitGroup.Go (Go 1.25), Once/OnceFunc/OnceValue/OnceValues, Cond.Wait/Signal/Broadcast, Pool.Get/Put and the GC, sync.Map (Load, Store, LoadOrStore, Range), atomic.Int64/Bool/Pointer[T]/Value and CAS loops, errgroup.SetLimit, semaphore.Weighted, singleflight, lock ordering, false sharing, sharded counters, the race detector and mutex profiles. Learning goal: Pick the right primitive for a piece of shared state, write it so that go vet and go test -race stay quiet, explain which write is visible to which goroutine and why, avoid lock-order deadlocks, and find contention with a mutex profile.
This page is the complete reference for Go's shared-memory synchronisation: every type in sync, the typed values in sync/atomic, and the three packages in golang.org/x/sync that practitioners use daily. It owns the API mechanics and their memory-model guarantees. Channels are taught in Goroutines & Channels and select in select: Multiplexing; cancellation is in context; worker pools and pipelines built on errgroup are in Worker Pools, Pipelines, Fan-Out/Fan-In; finding and explaining data races and deadlocks in general is in Race Conditions, the Race Detector, Deadlocks. Locks inside a database are a different subject: see Locks & Concurrency Control, and for locks across machines see Distributed Locking.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why Go has both channels and locks | Why it exists |
| Which Go version added what | Where it comes from |
Lock, Unlock, defer, lock scope, reentrancy | sync.Mutex |
passes lock by value, embedding a mutex | Copying a lock |
TryLock | TryLock |
| Fairness, starvation mode, spinning | Contention and starvation mode |
RLock, writer preference, upgrade | sync.RWMutex |
Add before go, wg.Go, reuse | sync.WaitGroup |
Lazy initialisation, OnceValue | sync.Once and friends |
Wait/Signal/Broadcast, spurious wakeups | sync.Cond |
| Buffer reuse, GC clearing | sync.Pool |
Concurrent map, LoadOrStore | sync.Map |
atomic.Int64, atomic.Pointer[T] | Atomic values |
| CAS loops, lock-free code | Compare-and-swap |
| Happens-before per primitive | The memory model |
| Lock ordering, lock hierarchy | Deadlocks with locks |
| Cache lines, padding, sharded counters | False sharing |
errgroup, semaphore, singleflight | golang.org/x/sync |
WARNING: DATA RACE | The race detector |
SetMutexProfileFraction | Mutex profiles |
| Exact fatal errors and panics | Mechanics |
| Mutex or channel or atomic | Choosing |
flock, Redis locks, APCu | For PHP/Laravel developers |
| Reproduce the outputs | Lab |
Everything in one minute
The primitives.
| Type | In plain words | Tiny example | Use it for |
|---|---|---|---|
sync.Mutex | One goroutine at a time | mu.Lock(); defer mu.Unlock() | Several fields that change together |
sync.RWMutex | Many readers or one writer | mu.RLock(); defer mu.RUnlock() | Read-mostly state with real work under the lock |
sync.WaitGroup | Count tasks, wait for zero | wg.Go(f); wg.Wait() | Wait for N goroutines |
sync.Once | Run a function exactly once | once.Do(setup) | Lazy initialisation |
sync.OnceValue(s) | Once that returns the result | cfg := sync.OnceValue(load) | Lazy singletons, Go 1.21+ |
sync.Cond | Sleep until another goroutine says "changed" | for !ok() { c.Wait() } | Rare; channels usually win |
sync.Pool | A free list the GC may empty | b := pool.Get().(*bytes.Buffer) | Reusing short-lived allocations |
sync.Map | A map safe for concurrent use | m.LoadOrStore(k, v) | Grow-only caches, disjoint keys |
atomic.Int64 etc. | One word updated indivisibly | hits.Add(1) | Counters, flags, pointer swaps |
errgroup.Group | WaitGroup plus first error plus limit | g.SetLimit(8); g.Go(f) | Bounded fan-out that can fail |
semaphore.Weighted | N units, take k at a time | sem.Acquire(ctx, 3) | Weighted admission (memory, connections) |
singleflight.Group | Concurrent identical calls share one | g.Do(key, load) | Cache-miss stampedes |
The guarantees (memory model, "synchronizes before").
| Primitive | Edge |
|---|---|
Mutex/RWMutex | Unlock n -> Lock m returns, for n < m; RUnlock -> next Lock |
Failed TryLock | No edge at all |
WaitGroup | Done (or return of a Go function) -> return of the Wait it unblocks |
Once | Return of f -> return of every once.Do(f) |
Cond | Signal/Broadcast -> return of the Wait it unblocks |
Pool | Put(x) -> the Get that returns x |
sync.Map | A write -> any read that observes it |
sync/atomic | A -> B when B observes A; all atomics are sequentially consistent |
The failures you will see.
| Message | Cause |
|---|---|
fatal error: all goroutines are asleep - deadlock! | Locked twice in one goroutine, recursive RLock behind a writer, Wait with nobody to Done |
fatal error: sync: unlock of unlocked mutex | Unlock without Lock (often a double Unlock) |
panic: sync: negative WaitGroup counter | More Done than Add |
fatal error: concurrent map writes | Plain map written from two goroutines |
WARNING: DATA RACE | -race saw unsynchronised conflicting accesses |
passes lock by value / assignment copies lock value | go vet copylocks: a struct with a mutex was copied |
WaitGroup.Add called from inside new goroutine | go vet waitgroup analyzer (Go 1.25) |
Why it exists
Goroutines share one address space. The moment two of them touch the same variable and at least one writes, you need a rule for who goes first and what the other one sees. Go's slogan, from Effective Go, is "Do not communicate by sharing memory; instead, share memory by communicating", and the next sentence is the reason this page exists: "This approach can be taken too far. Reference counts may be best done by putting a mutex around an integer variable, for instance." Channels are the right tool for handing data and ownership between goroutines; sync and sync/atomic are the right tool for protecting state that stays put.
| Simpler, coarser | Finer, riskier |
|---|---|
One Mutex around the whole struct | RWMutex, sharding, lock-free atomics |
| Channels: ownership moves, no shared state | Shared state with locks: less copying, more discipline |
sync.Once / OnceValue | Hand-rolled double-checked locking with atomics |
Plain map + Mutex | sync.Map: faster only for two specific access patterns |
| Allocate freely and let the GC work | sync.Pool: fewer allocations, more pitfalls |
An everyday picture. A small office. The single bathroom key on a hook is a Mutex: whoever holds it is alone inside, and taking it twice yourself makes no sense. The reading room is an RWMutex: any number of readers, but the cleaner needs it empty, and once the cleaner is waiting at the door the receptionist stops letting new readers in. The sign-out sheet at the end of a team outing is a WaitGroup: the bus leaves when every name is ticked. The "coffee machine set up" note is Once. The pile of reusable mugs is a Pool: handy, but the cleaner may wash them all away overnight. The tally counter at the entrance is an atomic: one click is one indivisible change.
Three common misunderstandings, up front
- "Go's mutex is like Java's
synchronized: I can lock it again in a nested call." No. Async.Mutexis not reentrant and is not owned by a goroutine; locking it twice in the same goroutine blocks forever (sync.Mutex). - "RWMutex is always faster for reads." Every
RLockstill writes a shared counter. With a short critical section a plainMutexis often faster; on the machine that produced this page's numbers, a read-only parallel benchmark measured 126.7 ns/op forRWMutexagainst 98.9 ns/op forMutex(sync.RWMutex). - "Atomics are a cheaper mutex." An atomic protects one word. Two atomics updated one after the other are not one consistent change; when an invariant spans fields, use a
Mutex(Atomic values).
Where it comes from
The texts that define this page are the sync package source and doc comments, the sync/atomic doc, The Go Memory Model (sections "Locks", "Once", "Atomic Values"), Effective Go on sharing, the Go FAQ entry "Why are map operations not defined to be atomic?", and the release notes listed below. The package comment sets the tone: "Other than the Once and WaitGroup types, most are intended for use by low-level library routines. Higher-level synchronization is better done via channels and communication."
| Go version | What arrived | Source |
|---|---|---|
| 1.0 | Mutex, RWMutex, WaitGroup, Once, Cond, sync/atomic functions | Package history |
| 1.3 | sync.Pool ("an efficient mechanism for implementing certain types of caches") | go1.3 notes |
| 1.4 | atomic.Value | go1.4 notes |
| 1.9 | sync.Map; "Mutex is now more fair" (starvation mode) | go1.9 notes |
| 1.13 | Pool "retains some objects across GCs" (victim cache) | go1.13 notes |
| 1.18 | Mutex.TryLock, RWMutex.TryLock, RWMutex.TryRLock | go1.18 notes |
| 1.19 | Memory model revised; typed atomics atomic.Int64, atomic.Pointer[T] and friends | go1.19 notes |
| 1.21 | OnceFunc, OnceValue, OnceValues | go1.21 notes |
| 1.23 | atomic And/Or; sync.Map.Clear | go1.23 notes |
| 1.24 | New sync.Map implementation, less contention on disjoint keys | go1.24 notes |
| 1.25 | WaitGroup.Go; go vet waitgroup analyzer | go1.25 notes |
Docs read for this page: Go 1.25 release notes and the sync sources served by go.dev at the time of writing; examples were run with the local Go 1.27.4 toolchain against a module that declares go 1.24.0.
The concept catalogue
sync.Mutex: Lock, Unlock and lock scope Must-know
In plain words: Lock waits until nobody else holds the mutex and then takes it; Unlock gives it back. Code between the two runs for one goroutine at a time. That region is the critical section, and the mutex protects whatever data you promise to touch only inside it.
Common misunderstanding: "The mutex belongs to the goroutine that locked it, so I can lock it again." The doc says the opposite: "A locked Mutex is not associated with a particular goroutine. It is allowed for one goroutine to lock a Mutex and then arrange for another goroutine to unlock it." Because there is no owner, there is no reentrancy: a second Lock from the same goroutine waits for an Unlock that will never come.
Definition: sync.Mutex is a mutual exclusion lock whose zero value is unlocked. It "must not be copied after first use". Unlock on an unlocked mutex is a run-time error (a fatal error, not a recoverable panic). The n-th Unlock synchronizes before the m-th Lock returns for n < m, so everything written before an Unlock is visible after the next Lock.
G1 (Deposit 10) G2 (Deposit 5) balance
1 mu.Lock() -> acquired 100
2 mu.Lock() -> blocks
3 balance = balance + 10 110
4 mu.Unlock() 110
5 -> acquired, sees 110
6 balance = balance + 5 115
7 mu.Unlock() 115Rules that keep it correct.
| Rule | Why |
|---|---|
Put mu next to the fields it guards, and say so in a comment | Readers know which fields need the lock |
Use a named, unexported field (mu sync.Mutex), not embedding | Embedding promotes Lock/Unlock into your public API; callers can lock your object from outside |
mu.Lock(); defer mu.Unlock() at the top of short methods | Unlock runs on every return path and on panic |
| Keep the critical section short: no I/O, no channel send, no callback | Holding a lock while blocking turns one slow call into a queue |
| Check and act under the same lock | if balance >= x then a separate locked balance -= x is a race on the decision |
| Never call a method that locks the same mutex while holding it | Not reentrant: self-deadlock |
| Use pointer receivers on types with a mutex | A value receiver copies the lock (Copying a lock) |
Lock scope with defer, and when not to defer. Since Go 1.14 most uses of defer "incur almost zero overhead compared to calling the deferred function directly" (release notes), so prefer it. Release early by hand only when the method continues with slow work that does not need the lock, for example: copy the data under the lock, Unlock, then encode or send it.
Real scenario: a wallet balance with deposit and withdraw; an in-memory rate-limit table; a connection registry in a WebSocket hub; a metrics struct with several related counters that a scrape must read consistently.
Fix / how to use it: the account below uses a named field, defer, check-and-act under one lock, TryLock for best-effort work and a lock hierarchy for transfers. The tests run under -race.
// Package mutex shows sync.Mutex used correctly: a named field (not
// embedded), short critical sections with defer, TryLock for an
// optional fast path, and a lock hierarchy that makes Transfer
// deadlock-free.
package mutex
import (
"errors"
"sync"
)
// ErrInsufficientFunds is returned when a withdrawal would go negative.
var ErrInsufficientFunds = errors.New("insufficient funds")
// Account is safe for concurrent use. Always pass *Account: copying the
// struct copies the mutex (go vet copylocks reports it).
type Account struct {
ID int // immutable after construction, readable without the lock
mu sync.Mutex // guards balance; unexported so callers cannot lock it
balance int64
}
// NewAccount returns an account with an opening balance.
func NewAccount(id int, opening int64) *Account {
return &Account{ID: id, balance: opening}
}
// Deposit adds amount. The lock covers only the shared state.
func (a *Account) Deposit(amount int64) {
a.mu.Lock()
defer a.mu.Unlock()
a.balance += amount
}
// Withdraw removes amount or returns ErrInsufficientFunds.
// Check and update happen under one lock: no check-then-act race.
func (a *Account) Withdraw(amount int64) error {
a.mu.Lock()
defer a.mu.Unlock()
if a.balance < amount {
return ErrInsufficientFunds
}
a.balance -= amount
return nil
}
// Balance returns a consistent snapshot.
func (a *Account) Balance() int64 {
a.mu.Lock()
defer a.mu.Unlock()
return a.balance
}
// TryDeposit deposits only if the lock is free right now. It is the rare
// legitimate TryLock use: best-effort work that may simply be skipped.
func (a *Account) TryDeposit(amount int64) bool {
if !a.mu.TryLock() {
return false
}
defer a.mu.Unlock()
a.balance += amount
return true
}
// Transfer moves amount between two accounts. Both locks are taken in
// ascending ID order (a lock hierarchy), so two opposite transfers can
// never hold one lock each and wait for the other.
func Transfer(from, to *Account, amount int64) error {
if from == to {
return nil
}
first, second := from, to
if second.ID < first.ID {
first, second = second, first
}
first.mu.Lock()
defer first.mu.Unlock()
second.mu.Lock()
defer second.mu.Unlock()
if from.balance < amount {
return ErrInsufficientFunds
}
from.balance -= amount
to.balance += amount
return nil
}$ go test -race ./mutex
ok academy/sync-primitives/mutex 1.344sCopying a lock and go vet copylocks Must-know
In plain words: a Mutex is a small struct of state bits. Copy it and you get a second, independent lock, maybe copied while locked. The two copies then protect nothing.
Common misunderstanding: "Only an explicit b := a copies." Copies also happen through value receivers, passing a struct by value, range over a slice of structs, returning a struct, and putting structs with mutexes in a map by value.
Definition: every type in sync carries the doc line "must not be copied after first use". go vet's copylocks analyzer ("check for locks erroneously passed by value") flags copies of any type that contains a sync.Locker or a noCopy marker. Real output for a struct with a value receiver:
$ go vet ./copy
copy/main.go:13:9: Get passes lock by value: lab/copy.Counter contains sync.Mutex
copy/main.go:21:7: assignment copies lock value to d: lab/copy.Counter contains sync.Mutex| Copy path | Example | Fix |
|---|---|---|
| Value receiver | func (c Counter) Get() int | func (c *Counter) Get() int |
| Pass by value | report(stats) | report(&stats) |
| Range copy | for _, a := range accounts { a.mu.Lock() } | for i := range accounts { accounts[i].mu.Lock() } or []*Account |
| Map value | map[string]Account | map[string]*Account |
| Embedding | type Cache struct { sync.Mutex; ... } | Named field mu sync.Mutex |
Embedding is legal and you will see it in older code; it is not a bug by itself. The cost is API leakage: cache.Lock() becomes callable by anyone, and the lock is now part of the type's contract. The structs chapter covers embedding in depth.
TryLock Good to know
In plain words: TryLock takes the lock if it is free and returns true, or returns false at once instead of waiting.
Common misunderstanding: "TryLock lets me check whether something is locked." By the time you act on the answer it may have changed. The doc warns: "while correct uses of TryLock do exist, they are rare, and use of TryLock is often a sign of a deeper problem in a particular use of mutexes."
Definition: added in Go 1.18 for Mutex and RWMutex (plus TryRLock). A successful call is equivalent to Lock; a failed call "does not establish any synchronizes before relation at all", and the memory model allows it to fail spuriously, even on an unlocked mutex.
G1 G2
1 mu.Lock()
2 mu.TryLock() -> false (skip the optional flush)
3 mu.Unlock()
4 mu.TryLock() -> true; flush; mu.Unlock()Real scenario: an opportunistic background flush that may simply skip a round; a metrics sampler that must never stall a request path. If you find yourself looping on TryLock, you wanted Lock, a channel, or context-aware waiting with semaphore.Weighted.
Contention, fairness and starvation mode Important
In plain words: when many goroutines want one mutex, they queue. By default Go lets a goroutine that is already running on a CPU grab the lock ahead of a waiter that was just woken, which is fast but unfair. If a waiter is starved for more than a millisecond, the mutex switches to strict hand-off until the queue calms down.
Common misunderstanding: "Go mutexes are FIFO." Only in starvation mode. In normal mode, a goroutine may re-acquire a mutex several times in a row even while others wait.
Definition (from the runtime comment in internal/sync/mutex.go): "In normal mode waiters are queued in FIFO order, but a woken up waiter does not own the mutex and competes with new arriving goroutines over the ownership." "If a waiter fails to acquire the mutex for more than 1ms, it switches mutex to the starvation mode." In starvation mode "ownership of the mutex is directly handed off from the unlocking goroutine to the waiter at the front of the queue" and new arrivals neither try to acquire nor spin. The mutex goes back to normal mode when the new owner is the last waiter or waited less than 1 ms. "Normal mode has considerably better performance ... Starvation mode is important to prevent pathological cases of tail latency." The Go 1.9 release notes summarise this as "Mutex is now more fair."
time G1 (holder) G2 (woken waiter) G3..G9 (new arrivals)
1 0.0ms Unlock
2 0.0ms wakes, tries CAS G3 spins, wins CAS
3 0.4ms requeued at front G4 wins, G5 wins ...
4 1.1ms waited > 1ms -> sets mutexStarving
5 1.2ms (G9 Unlock) ownership handed to G2 new arrivals queue at tail
6 1.3ms G2 last waiter? -> back to normal modeContention signs and fixes.
| Symptom | Likely cause | Fix |
|---|---|---|
| CPU not saturated, latency high under load | Goroutines queue on one mutex | Mutex profile (Mutex profiles), shorten the critical section |
| p99 spikes but p50 fine | Unfair normal mode, long holds | Move I/O out of the lock; shard the state |
| Hot counter in a profile | Every request updates one variable | Atomic, or a sharded counter (False sharing) |
| Read-heavy map lock at the top of the profile | Many readers serialised | RWMutex if the read work is non-trivial, sync.Map for grow-only, or copy-on-write with atomic.Pointer |
sync.RWMutex: readers, writers and writer preference Must-know
In plain words: many goroutines may hold the read lock together (RLock/RUnlock); a writer (Lock/Unlock) needs everyone out. As soon as a writer is waiting, new readers wait too, so writers cannot starve.
Common misunderstanding (two of them): "I can take RLock again inside a function that already holds it." Not safely: if a writer arrives between the two calls, the second RLock waits for the writer, and the writer waits for your first RLock. And: "I can upgrade a read lock to a write lock." There is no upgrade; Lock while holding RLock deadlocks.
Definition: "The lock can be held by an arbitrary number of readers or a single writer." "If any goroutine calls Lock while the lock is already held by one or more readers, concurrent calls to RLock will block until the writer has acquired (and released) the lock ... Note that this prohibits recursive read-locking. A RLock cannot be upgraded into a Lock, nor can a Lock be downgraded into a RLock." For memory: the n-th Unlock synchronizes before the m-th Lock; each RLock sees some n-th Unlock, and its RUnlock synchronizes before the n+1-th Lock.
R1 W R3
1 RLock() -> ok
2 Lock() -> waits for R1
3 RLock() -> waits (writer pending)
4 RLock() again -> waits for W -- R1 waits W, W waits R1: deadlockReal output of exactly that program:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [sync.RWMutex.RLock]:
sync.runtime_SemacquireRWMutexR(0x989680?, 0x48?, 0x0?)When RWMutex is slower. Each RLock and RUnlock is an atomic add on a shared readerCount, so readers on different cores still fight over one cache line. A writer must also wait for every active reader to leave. Measured on this page's machine (Apple M4 Pro, 12 goroutines, read-only map lookup):
| Benchmark | ns/op |
|---|---|
BenchmarkReadRWMutex-12 | 126.7 |
BenchmarkReadMutex-12 | 98.92 |
Use RWMutex when reads dominate and the read-side work is long enough (iterating a structure, formatting, copying) that parallel readers win back the extra cost. Measure with b.RunParallel before switching.
Upgrade pattern: release the read lock, take the write lock, check again.
// Package rwcache is a read-mostly cache guarded by sync.RWMutex. It shows
// that a read lock cannot be upgraded: GetOrLoad releases the read lock,
// takes the write lock and checks again.
package rwcache
import "sync"
// Cache maps string keys to values of type V.
type Cache[V any] struct {
mu sync.RWMutex
m map[string]V
}
// New returns an empty cache.
func New[V any]() *Cache[V] {
return &Cache[V]{m: make(map[string]V)}
}
// Get takes the shared (read) lock: many readers proceed in parallel.
func (c *Cache[V]) Get(key string) (V, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok := c.m[key]
return v, ok
}
// Set takes the exclusive (write) lock.
func (c *Cache[V]) Set(key string, v V) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[key] = v
}
// GetOrLoad returns the cached value or calls load once per miss window.
// Calling c.mu.Lock while holding RLock would deadlock, so the read lock is
// released first and the map is checked again under the write lock
// (another goroutine may have filled it in between).
func (c *Cache[V]) GetOrLoad(key string, load func() V) V {
c.mu.RLock()
v, ok := c.m[key]
c.mu.RUnlock()
if ok {
return v
}
c.mu.Lock()
defer c.mu.Unlock()
if v, ok := c.m[key]; ok { // re-check: we lost the race
return v
}
v = load() // runs under the write lock; keep it short
c.m[key] = v
return v
}
// Len reports the number of entries.
func (c *Cache[V]) Len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.m)
}sync.WaitGroup: Add, Done, Wait and WaitGroup.Go Must-know
In plain words: a WaitGroup is a counter. Add(n) raises it, Done() lowers it by one, and Wait() sleeps until it reaches zero. Since Go 1.25, wg.Go(f) does the Add(1), starts the goroutine and calls Done when f returns.
Common misunderstanding: "I can call wg.Add(1) at the top of the goroutine." Then Wait may run before any goroutine has started, see zero and return early. The doc: "calls with a positive delta that occur when the counter is zero must happen before a Wait ... Typically this means the calls to Add should execute before the statement creating the goroutine." Go 1.25's vet catches it; real output:
$ go vet ./wgvet
wgvet/main.go:9:10: WaitGroup.Add called from inside new goroutineDefinition: WaitGroup is "a counting semaphore typically used to wait for a group of goroutines or tasks to finish". Done is Add(-1); a negative counter panics with sync: negative WaitGroup counter. A call to Done "synchronizes before" the return of any Wait it unblocks, so results written by workers are visible after Wait. For reuse: "new Add calls must happen after all previous Wait calls have returned". WaitGroup.Go's doc adds that "The function f must not panic"; if it does, Go deliberately does not call Done, so the crash is not raced by an early Wait return.
main worker 1 worker 2
1 wg.Add(1); go w1
2 wg.Add(1); go w2
3 wg.Wait() -> counter 2, sleeps
4 out[0] = 1; Done -> 1
5 out[1] = 4; Done -> 0
6 Wait returns; reads out (Done synchronizes before Wait returns)| Mistake | Symptom | Fix |
|---|---|---|
Add inside the goroutine | Wait returns early, results missing, vet warning | Add before go, or wg.Go |
Forgot Done on an error path | Wait hangs, all goroutines are asleep | defer wg.Done() first line, or wg.Go |
Done twice | panic: sync: negative WaitGroup counter | One Done per Add(1) |
Passed wg by value | Wait never returns (copy counted) | Pass *sync.WaitGroup, vet copylocks warns |
Reused before Wait returned | sync: WaitGroup is reused before previous Wait has returned | New round only after Wait |
| Need the first error | WaitGroup has no error channel | errgroup.Group (x/sync) |
Fix / how to use it: both shapes, with WaitGroup.Go in a file built only on Go 1.25 and newer (//go:build go1.25), so the module still builds on 1.24.
// Package waitgroup shows the two correct WaitGroup shapes: Add before
// the go statement (every Go version) and WaitGroup.Go (Go 1.25+, in
// go125.go).
package waitgroup
import "sync"
// SquareAll squares every input concurrently and waits for all of them.
// Each goroutine writes its own index, so no lock is needed for out.
func SquareAll(in []int) []int {
out := make([]int, len(in))
var wg sync.WaitGroup
for i, v := range in {
wg.Add(1) // before go: Wait cannot see a zero counter too early
go func() {
defer wg.Done() // defer: Done runs even if the body returns early
out[i] = v * v
}()
}
wg.Wait() // every Done "synchronizes before" this return
return out
}
// Batches reuses one WaitGroup for several rounds. A new round's Add only
// starts after the previous Wait has returned, which the loop guarantees.
func Batches(rounds, perRound int, work func(round, i int)) {
var wg sync.WaitGroup
for r := 0; r < rounds; r++ {
for i := 0; i < perRound; i++ {
wg.Add(1)
go func() {
defer wg.Done()
work(r, i)
}()
}
wg.Wait()
}
}//go:build go1.25
package waitgroup
import "sync"
// SquareAllGo is SquareAll written with WaitGroup.Go (Go 1.25). Go does
// the Add(1) before starting the goroutine and the Done when f returns,
// so the two classic mistakes cannot be written.
func SquareAllGo(in []int) []int {
out := make([]int, len(in))
var wg sync.WaitGroup
for i, v := range in {
wg.Go(func() {
out[i] = v * v
})
}
wg.Wait()
return out
}sync.Once, OnceFunc, OnceValue, OnceValues: lazy initialization Must-know
In plain words: once.Do(f) runs f the first time anybody calls it; everybody else waits until it has finished and then skips it. The Go 1.21 helpers wrap the same idea into a function you call: OnceFunc for side effects, OnceValue for one result, OnceValues for a result and an error.
Common misunderstanding: "If initialisation fails, Once will try again next time." It will not. If f returns an error you stored, every later caller gets that error; if f panics, Do "considers it to have returned; future calls of Do return without calling f." The OnceValue family differs: "If f panics, the returned function will panic with the same value on every call."
Definition: "The completion of a single call of f() from once.Do(f) is synchronized before the return of any call of once.Do(f)" (memory model). So the values f wrote are visible to every caller without another lock. Do holds an internal mutex while f runs: "if f causes Do to be called, it will deadlock." The source also explains why a single CompareAndSwap is not a correct Once: "Do guarantees that when it returns, f has finished."
G1 G2 G3
1 once.Do(load) -> runs load
2 once.Do(load) -> blocks
3 load writes cfg
4 load returns -> returns, sees cfg
5 once.Do(load) -> returns at once (fast path)| Variant | Signature | On panic | Typical use |
|---|---|---|---|
sync.Once | once.Do(func()) | Marked done; later calls skip | Struct-scoped init, close-once |
sync.OnceFunc | func(f func()) func() | Re-panics every call | Idempotent Close, one-time log |
sync.OnceValue | func(f func() T) func() T | Re-panics every call | Lazy table, compiled regexp |
sync.OnceValues | func(f func() (T, error)) func() (T, error) | Re-panics every call | Load config or a client once |
package init() | runs at program start | Crashes the program | Cheap, always-needed setup |
Real scenario: a database pool created on first request; a parsed template set; a Close method that may be called from shutdown and from a deferred cleanup; a lookup table needed only by one rarely used endpoint.
// Package once shows lazy initialisation with sync.Once and the Go 1.21
// helpers OnceFunc, OnceValue and OnceValues.
package once
import (
"errors"
"os"
"sync"
)
// Config is loaded at most once per process.
type Config struct {
DSN string
}
// Loader wraps sync.Once by hand: the classic pre-1.21 shape.
type Loader struct {
once sync.Once
cfg *Config
err error
read func() (string, error)
}
// NewLoader takes the function that reads the raw setting.
func NewLoader(read func() (string, error)) *Loader {
return &Loader{read: read}
}
// Get runs read exactly once; every caller, concurrent or later, sees the
// same result. The return of the once.Do function "synchronizes before"
// the return of every Do, so cfg and err need no extra lock.
func (l *Loader) Get() (*Config, error) {
l.once.Do(func() {
dsn, err := l.read()
if err != nil {
l.err = err // cached: Once never retries
return
}
l.cfg = &Config{DSN: dsn}
})
return l.cfg, l.err
}
// ErrNoDSN is returned when APP_DSN is unset.
var ErrNoDSN = errors.New("APP_DSN is not set")
// LoadConfig is the same thing in one line with OnceValues (Go 1.21).
var LoadConfig = sync.OnceValues(func() (*Config, error) {
dsn, ok := os.LookupEnv("APP_DSN")
if !ok {
return nil, ErrNoDSN
}
return &Config{DSN: dsn}, nil
})
// expensiveTable is computed on first use, then shared.
var expensiveTable = sync.OnceValue(func() []int {
t := make([]int, 256)
for i := range t {
t[i] = i * i
}
return t
})
// Square uses the lazily built table.
func Square(b byte) int { return expensiveTable()[b] }
// NewCloser returns a close function that is safe to call many times;
// OnceFunc makes the side effect run once.
func NewCloser(closeFn func()) func() {
return sync.OnceFunc(closeFn)
}sync.Cond: Wait, Signal, Broadcast Good to know
In plain words: a condition variable lets a goroutine holding a lock say "wake me when this changes" and sleep without holding the lock. Another goroutine changes the state and calls Signal (wake one) or Broadcast (wake all).
Common misunderstanding: "I need the for loop because of spurious wakeups, as in POSIX." Go's doc says: "Unlike in other systems, Wait cannot return unless awoken by Broadcast or Signal." There is no spurious wakeup in Go. You still need the loop, because between the wake-up and re-acquiring the lock another goroutine may have consumed the item: "the caller typically cannot assume that the condition is true when Wait returns. Instead, the caller should Wait in a loop."
Definition: Cond has a Locker L "which must be held when changing the condition and when calling the Wait method". Wait "atomically unlocks c.L and suspends execution of the calling goroutine. After later resuming execution, Wait locks c.L before returning." Signal/Broadcast synchronize before the Wait they unblock. The doc itself recommends channels for most uses: "Broadcast corresponds to closing a channel, and Signal corresponds to sending on a channel."
taker T1 taker T2 producer P
1 Lock; len==0 -> Wait (unlocks)
2 Lock; len==0 -> Wait
3 Lock; append x; Signal; Unlock
4 wakes, relocks; len==1 -> takes x
5 Unlock
6 Close: Broadcast
7 wakes; len==0 && closed -> ErrClosed| Need | sync.Cond | Channel |
|---|---|---|
| Wake one waiter | Signal | send one value |
| Wake all waiters | Broadcast | close(ch) (once only) |
| Timeout or cancel while waiting | Not possible | select with ctx.Done() or a timer |
| Wait on a complex predicate over shared state | Natural | Awkward |
| Wake all, many times | Broadcast again | Needs a new channel each time |
// Package cond implements a bounded blocking queue twice: with sync.Cond
// (the textbook shape) and with a buffered channel (what you usually want).
package cond
import (
"errors"
"sync"
)
// ErrClosed is returned by Put after Close, and by Take once drained.
var ErrClosed = errors.New("queue closed")
// CondQueue is a FIFO with a capacity. Two condition variables share one
// mutex: notEmpty wakes takers, notFull wakes putters.
type CondQueue[T any] struct {
mu sync.Mutex
notEmpty *sync.Cond
notFull *sync.Cond
items []T
cap int
closed bool
}
// NewCondQueue returns a queue that holds at most capacity items.
func NewCondQueue[T any](capacity int) *CondQueue[T] {
q := &CondQueue[T]{cap: capacity}
q.notEmpty = sync.NewCond(&q.mu)
q.notFull = sync.NewCond(&q.mu)
return q
}
// Put blocks while the queue is full.
func (q *CondQueue[T]) Put(v T) error {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.items) == q.cap && !q.closed { // loop, never if
q.notFull.Wait() // unlocks mu, sleeps, relocks mu
}
if q.closed {
return ErrClosed
}
q.items = append(q.items, v)
q.notEmpty.Signal() // one taker can make progress
return nil
}
// Take blocks while the queue is empty and open.
func (q *CondQueue[T]) Take() (T, error) {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.items) == 0 && !q.closed {
q.notEmpty.Wait()
}
var zero T
if len(q.items) == 0 { // closed and drained
return zero, ErrClosed
}
v := q.items[0]
q.items[0] = zero // drop the reference for the GC
q.items = q.items[1:]
q.notFull.Signal()
return v, nil
}
// Close wakes every waiter: Broadcast, because all of them must re-check.
func (q *CondQueue[T]) Close() {
q.mu.Lock()
q.closed = true
q.mu.Unlock()
q.notEmpty.Broadcast()
q.notFull.Broadcast()
}
// ChanQueue is the same contract with a buffered channel. Signal maps to a
// send, Broadcast maps to close. It also works with select and timeouts,
// which Cond.Wait cannot.
type ChanQueue[T any] struct {
ch chan T
}
// NewChanQueue returns a queue that holds at most capacity items.
func NewChanQueue[T any](capacity int) *ChanQueue[T] {
return &ChanQueue[T]{ch: make(chan T, capacity)}
}
// Put blocks while full. Calling Put after Close panics ("send on closed
// channel"), so only the single producer may call Close.
func (q *ChanQueue[T]) Put(v T) { q.ch <- v }
// Take blocks while empty; ok is false once closed and drained.
func (q *ChanQueue[T]) Take() (T, bool) {
v, ok := <-q.ch
return v, ok
}
// Close signals "no more items" to every taker.
func (q *ChanQueue[T]) Close() { close(q.ch) }sync.Pool: Get, Put and buffer reuse Important
In plain words: a Pool is a bag of spare objects. Get hands you one (or calls New if the bag is empty), Put gives it back. The garbage collector may empty the bag at any time, so a pool is a performance hint, never storage.
Common misunderstanding: "A pool is a connection pool." It is not: items vanish without notice, so it cannot hold anything with identity or a lifecycle (connections, files). Database connection pools are a different mechanism: see Connection Pooling.
Definition: "Any item stored in the Pool may be removed automatically at any time without notification." "Pool's purpose is to cache allocated but unused items for later reuse, relieving pressure on the garbage collector." The implementation keeps a per-P (per logical processor) private slot and a shared chain; at the start of every GC the runtime moves the primary cache to a victim cache and drops the previous victim, so objects survive at most one extra cycle (Go 1.13: Pool "retains some objects across GCs"). Put(x) synchronizes before the Get that returns x.
GC cycle pool.local pool.victim Get() finds
1 before [b1 b2 b3] [] b1 (local hit)
2 GC #1 [] [b2 b3] b2 (victim hit)
3 GC #2 [] [] New() -> fresh buffer| Pitfall | What happens | Fix |
|---|---|---|
Not resetting on Get | Previous user's bytes leak into your output | b.Reset() after Get |
Put of a value type ([]byte) | Put boxes the slice header: one allocation per Put (staticcheck reports it as SA6002) | Store pointers (*bytes.Buffer, *[]byte) |
| Keeping huge buffers | One 10 MB request pins 10 MB per P forever | Drop items above a cap before Put |
Using the object after Put | Another goroutine is now writing it | Put last; copy what you return |
| Pooling cheap objects | Pool overhead exceeds new | Benchmark with -benchmem first |
| Expecting persistence | Items disappear each GC | Treat a miss as normal |
Measured on this page's machine for the log-line renderer below: 144 B/op and 7 allocs/op with the pool against 256 B/op and 9 allocs/op without. The gain is modest here because fmt itself already pools its buffers, which is the doc's own example of good use.
// Package pool reuses bytes.Buffer values with sync.Pool. It stores
// pointers, resets on Get, and refuses to keep oversized buffers.
package pool
import (
"bytes"
"fmt"
"sync"
)
// maxKept caps the capacity of a buffer that goes back to the pool. One
// 10 MB request must not pin 10 MB per P for the rest of the process.
const maxKept = 64 << 10
var bufPool = sync.Pool{
// New runs when the pool is empty (always after the GC cleared it).
New: func() any { return new(bytes.Buffer) },
}
func getBuf() *bytes.Buffer {
b := bufPool.Get().(*bytes.Buffer)
b.Reset() // a pooled value carries the previous user's data
return b
}
func putBuf(b *bytes.Buffer) {
if b.Cap() > maxKept {
return // let the GC free it
}
bufPool.Put(b) // a pointer: no allocation on Put
}
// RenderLine formats one log line using a pooled buffer. The returned
// string is a copy, so the buffer can be reused safely.
func RenderLine(level, msg string, attrs map[string]string, keys []string) string {
b := getBuf()
defer putBuf(b)
fmt.Fprintf(b, "level=%s msg=%q", level, msg)
for _, k := range keys {
fmt.Fprintf(b, " %s=%q", k, attrs[k])
}
return b.String()
}
// RenderLineNoPool is the baseline for the benchmark.
func RenderLineNoPool(level, msg string, attrs map[string]string, keys []string) string {
var b bytes.Buffer
fmt.Fprintf(&b, "level=%s msg=%q", level, msg)
for _, k := range keys {
fmt.Fprintf(&b, " %s=%q", k, attrs[k])
}
return b.String()
}sync.Map: Load, Store, LoadOrStore, Range Important
In plain words: a map that many goroutines can use without your own lock. It is fast in two situations and worse than map plus Mutex in most others.
Common misunderstanding: "Use sync.Map whenever a map is shared." The doc: "The Map type is specialized. Most code should use a plain Go map instead, with separate locking or coordination, for better type safety and to make it easier to maintain other invariants along with the map content."
Definition: sync.Map "is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys." Methods: Load, Store, LoadOrStore, LoadAndDelete, Delete, Swap, CompareAndSwap, CompareAndDelete, Range, Clear (1.23). Keys and values are any. Range is not a snapshot: it may or may not reflect concurrent stores. Go 1.24 replaced the implementation (a concurrent hash trie), so "modifications of disjoint sets of keys are much less likely to contend on larger maps".
G1 G2
1 m.Load("re") -> miss m.Load("re") -> miss
2 c1 := compile("re") c2 := compile("re")
3 m.LoadOrStore("re", c1) -> c1, false
4 m.LoadOrStore("re", c2) -> c1, true (c2 discarded)| Option | Type safety | Best for | Weak at |
|---|---|---|---|
map + Mutex | Full | General use, invariants across keys | Very high read contention |
map + RWMutex | Full | Read-mostly with non-trivial reads | Tiny reads (see benchmark) |
sync.Map | any (wrap it) | Grow-only caches, disjoint key sets | Frequent overwrite of shared keys, len |
Sharded map + Mutex per shard | Full | Large hot maps | Cross-shard operations |
atomic.Pointer[map[K]V] copy-on-write | Full | Rarely changing lookup tables | Frequent writes (copies the whole map) |
A plain map written by two goroutines is not a data race the runtime ignores: it is detected and kills the process with fatal error: concurrent map writes (the FAQ explains why maps are not atomic by default: requiring a mutex on every map operation "would slow down most programs and add safety to few"). A small generic wrapper restores type safety:
// Package syncmap shows when sync.Map fits (an append-only, read-mostly
// cache) and a tiny generic wrapper that restores type safety.
package syncmap
import "sync"
// Map is a typed facade over sync.Map. The zero value is ready to use.
type Map[K comparable, V any] struct {
m sync.Map
}
// Load returns the value for key.
func (m *Map[K, V]) Load(key K) (V, bool) {
v, ok := m.m.Load(key)
if !ok {
var zero V
return zero, false
}
return v.(V), true
}
// Store sets the value for key.
func (m *Map[K, V]) Store(key K, v V) { m.m.Store(key, v) }
// LoadOrStore keeps the first value stored for key. loaded reports
// whether an earlier value won.
func (m *Map[K, V]) LoadOrStore(key K, v V) (actual V, loaded bool) {
a, loaded := m.m.LoadOrStore(key, v)
return a.(V), loaded
}
// Delete removes key.
func (m *Map[K, V]) Delete(key K) { m.m.Delete(key) }
// Range calls f for each entry until f returns false. It is not a
// snapshot: concurrent stores may or may not be seen.
func (m *Map[K, V]) Range(f func(K, V) bool) {
m.m.Range(func(k, v any) bool { return f(k.(K), v.(V)) })
}
// Compiled is the typical use: compile-once cache keyed by pattern.
type Compiled struct{ Pattern string }
var cache Map[string, *Compiled]
// Get returns the shared *Compiled for pattern. Two goroutines may both
// build one on a miss; LoadOrStore makes sure only one is kept.
func Get(pattern string) *Compiled {
if c, ok := cache.Load(pattern); ok {
return c
}
c, _ := cache.LoadOrStore(pattern, &Compiled{Pattern: pattern})
return c
}sync/atomic: Int64, Bool, Pointer, Value and their operations Must-know
In plain words: an atomic operation reads or changes one machine word so that no other goroutine can see it half done. hits.Add(1) from a thousand goroutines adds exactly a thousand.
Common misunderstanding: "atomic.Load is only about tearing; it does not order other memory." In Go it does: "If the effect of an atomic operation A is observed by atomic operation B, then A is synchronized before B. All the atomic operations executed in a program behave as though executed in some sequentially consistent order" (memory model). Go has no relaxed or acquire-only atomics; the Go 1.19 notes state: "Go only provides sequentially consistent atomics, not any of the more relaxed forms found in other languages."
Definition: since Go 1.19 the package has types atomic.Bool, Int32, Int64, Uint32, Uint64, Uintptr, Pointer[T] and the older Value. Their methods are Load, Store, Swap, CompareAndSwap, plus Add for integers and (Go 1.23) And/Or. The package doc defines them: swap is old = *addr; *addr = new; return old; compare-and-swap is if *addr == old { *addr = new; return true }; return false; add is *addr += delta; return *addr. The typed values cannot be accessed non-atomically by mistake and "types Int64 and Uint64 are automatically aligned", which the old AddInt64(&x, 1) functions on 32-bit platforms did not guarantee.
G1 G2 hits (atomic.Int64)
1 hits.Add(1) -> 1 1
2 hits.Add(1) -> 2 2
3 hits.Load() -> 2 2
-- with a plain int and hits++: both may read 0 and both write 1| Type | Methods | Typical use |
|---|---|---|
atomic.Int64 / Uint64 | Add, Load, Store, Swap, CompareAndSwap, And, Or | Request counters, IDs, high-water marks |
atomic.Int32 / Uint32 | Same | Small counters, state enums |
atomic.Bool | Load, Store, Swap, CompareAndSwap | Shutdown flag, "already started" |
atomic.Pointer[T] | Load, Store, Swap, CompareAndSwap | Copy-on-write config, routing tables |
atomic.Value | Load, Store, Swap, CompareAndSwap | Pre-generics code; one concrete type only, Store(nil) panics |
Functions atomic.AddInt64(&x, 1) | Same operations on plain variables | Legacy code; every access must be atomic |
Real scenario: a request counter scraped by Prometheus; a stopping flag checked by every handler; hot-reloading a feature-flag snapshot without stopping readers; tracking the maximum queue depth seen.
// Package atomics shows the typed sync/atomic values (Go 1.19+): a
// counter, a one-shot flag, a hot-reloaded config pointer, a CAS loop and
// atomic.Value.
package atomics
import (
"sync/atomic"
)
// Stats are lock-free counters. The typed values cannot be read or
// written non-atomically by mistake, and Int64 is 64-bit aligned even on
// 32-bit platforms.
type Stats struct {
Requests atomic.Int64
Errors atomic.Int64
}
// Observe records one request.
func (s *Stats) Observe(failed bool) {
s.Requests.Add(1)
if failed {
s.Errors.Add(1)
}
}
// Server shuts down once, from any goroutine.
type Server struct {
stopping atomic.Bool
}
// Stop returns true only for the caller that flipped the flag.
func (s *Server) Stop() bool {
return s.stopping.CompareAndSwap(false, true)
}
// Stopping is a cheap check for request handlers.
func (s *Server) Stopping() bool { return s.stopping.Load() }
// Config is immutable once published: readers never see a half-written one.
type Config struct {
RateLimit int
Features map[string]bool
}
// Holder publishes Config snapshots with atomic.Pointer (copy-on-write).
type Holder struct {
p atomic.Pointer[Config]
}
// NewHolder stores the first snapshot.
func NewHolder(c *Config) *Holder {
h := &Holder{}
h.p.Store(c)
return h
}
// Get is wait-free for readers.
func (h *Holder) Get() *Config { return h.p.Load() }
// Reload swaps in a new snapshot and returns the old one.
func (h *Holder) Reload(c *Config) *Config { return h.p.Swap(c) }
// UpdateMax raises m to v if v is larger: the compare-and-swap retry loop.
func UpdateMax(m *atomic.Int64, v int64) {
for {
cur := m.Load()
if v <= cur {
return
}
if m.CompareAndSwap(cur, v) {
return
}
// another goroutine changed m between Load and CAS: retry
}
}
// Version holds a value of one concrete type in atomic.Value (pre-generics API).
var Version atomic.Value
func init() { Version.Store("v1.0.0") }
// CurrentVersion type-asserts the stored value.
func CurrentVersion() string { return Version.Load().(string) }Compare-and-swap (CAS) and lock-free code Important
In plain words: CAS says "set it to new, but only if it is still old". If someone changed it in between, you read again and retry. Code built only from such retries, never blocking on a lock, is called lock-free.
Common misunderstanding: "Lock-free means faster." Under heavy contention a CAS loop spins and retries while a mutex parks waiters; lock-free code is also much harder to prove correct (the ABA problem, multi-word invariants). The atomic package doc is blunt: "These functions require great care to be used correctly. Except for special, low-level applications, synchronization is better done with channels or the facilities of the sync package."
Definition: CompareAndSwap(old, new) atomically compares and conditionally replaces, returning whether it swapped. A CAS loop is: load, compute, CAS, retry on failure. The update must be a pure function of the loaded value.
G1 (UpdateMax 7) G2 (UpdateMax 9) max
1 cur := Load() -> 5 5
2 cur := Load() -> 5 5
3 CAS(5, 9) -> true 9
4 CAS(5, 7) -> false (now 9) 9
5 cur := Load() -> 9; 7 <= 9 -> return 9| Pattern | Primitive | Safe for |
|---|---|---|
| Counter | Add | One word |
| One-shot flag | Bool.CompareAndSwap(false, true) | "only one caller wins" |
| Max/min tracking | CAS loop on Int64 | One word, monotonic |
| Copy-on-write snapshot | Pointer[T].Store of a new immutable value | Many fields, readers never lock |
| Lock-free stack/queue | CAS on Pointer[node] | Experts only; beware ABA and memory reuse |
Copy-on-write with atomic.Pointer[T] is the lock-free pattern most services should know: build a new immutable value, then Store it. Readers Load and keep using their snapshot. Writers that may race need a mutex around build-and-store, or a CAS loop, so that two writers do not lose each other's change.
The memory model: happens-before for each primitive Must-know
In plain words: a goroutine is guaranteed to see another goroutine's write only if a chain of synchronisation connects the write to the read. Each primitive on this page is one such link.
Common misunderstanding: "On x86 writes are visible immediately, so a plain bool flag works." The compiler may keep the value in a register, hoist the read out of the loop, or reorder stores; the race detector flags it regardless of CPU. The memory model only promises sequentially consistent behaviour to race-free programs ("data-race-free programs execute in a sequentially consistent manner").
Definition: the memory model defines "synchronized before" edges; together with program order inside a goroutine they form happens-before. A read is allowed to observe a write when the write happens before it and no other write intervenes. The edges per primitive are in the table in Everything in one minute; the canonical mutex example from the memory model is "guaranteed to print hello, world": f writes a then calls Unlock; main's second Lock returns after that Unlock, then prints a.
G1 G2
1 cfg = load()
2 ready = true (plain bool)
3 for !ready {} -- may spin forever: no edge
4 use(cfg) -- may see a stale cfg
fix: ready as atomic.Bool, or close(readyCh), or once.DoThe page Pointers & Memory Model Basics introduces happens-before; this section is the per-primitive list.
Deadlocks with locks: lock ordering and lock hierarchy Must-know
In plain words: two goroutines each hold one lock and wait for the other's. Neither can move. With mutexes the cure is boring and reliable: everyone takes locks in the same order.
Common misunderstanding: "The runtime detects deadlocks." It detects only the case where every goroutine in the program is blocked (fatal error: all goroutines are asleep - deadlock!). In a server, the HTTP listener goroutine is still alive, so two stuck handlers just hang forever with no message.
Definition: a deadlock needs mutual exclusion, hold-and-wait, no preemption and a circular wait. Lock ordering breaks the circle: define a global order (by account ID, by address, by level in the object tree) and always acquire in that order. A lock hierarchy is the same idea for layers: a goroutine holding a level-2 lock may take level-3 locks but never level-1.
G1 Transfer(A -> B) G2 Transfer(B -> A)
1 A.mu.Lock()
2 B.mu.Lock()
3 B.mu.Lock() -> waits for G2
4 A.mu.Lock() -> waits for G1 deadlock
fix: both lock min(ID) first -> G2 also starts with A, waits, then proceeds| Deadlock shape | Example | Prevention |
|---|---|---|
| Lock-order inversion | Two transfers in opposite directions | Order by ID (snippet) |
| Self-deadlock | Method holding mu calls another method that locks mu | Split into locked public and unlocked private (fooLocked) methods |
Recursive RLock | Reader calls a helper that RLocks again | Never re-enter; pass state down |
| Lock plus channel | Hold mu, send on a full channel whose reader needs mu | Never block on channels under a lock |
| Once recursion | once.Do(f) where f calls once.Do | Restructure init |
Wait without Done | Early return skipped Done | defer wg.Done() or wg.Go |
The same theory applies inside a database (Deadlocks: Detection & Avoidance) where the engine does detect cycles; and the general debugging workflow for hung programs (goroutine dumps, SIGQUIT) is in Race Conditions, the Race Detector, Deadlocks.
False sharing, cache lines, padding and sharded counters Good to know
In plain words: CPUs move memory in cache lines (64 bytes on most x86-64 and many ARM cores, 128 on Apple M-series: sysctl hw.cachelinesize prints 128 on the lab machine). Two counters in the same line, updated by two cores, force the line to bounce between them even though they are logically independent. That is false sharing. Padding puts each hot variable on its own line.
Common misunderstanding: "An atomic counter scales with cores." One atomic counter is one cache line every core must own in turn. It is correct, and it is a serial bottleneck.
Definition: a sharded counter keeps N independent counters (one per P or per worker) and sums them on read. Padding each shard to a full cache line (_ [cacheLine - 8]byte) prevents neighbouring shards from false sharing. Reads cost O(N) and are not an atomic snapshot.
Measured on this page's machine (12 goroutines, b.RunParallel):
| Benchmark | ns/op | Why |
|---|---|---|
BenchmarkSingleAtomic-12 | 53.37 | One line, every core contends |
BenchmarkShardedUnpadded-12 | 32.55 | Separate counters, shared lines |
BenchmarkShardedPadded-12 | 0.1786 | One line per shard, no ping-pong |
core 0 (shard 0) core 1 (shard 1) cache line L (both shards)
1 Add -> owns L (Modified)
2 Add -> steals L, core 0 invalidated
3 Add -> steals L back ping-pong every op
padded: shard 0 in line L0, shard 1 in line L1 -> no transfersgolang.org/x/sys/cpu exports a CacheLinePad type for the same purpose; the snippet uses a constant to stay on the standard library. The system-level version of this idea, splitting one hot row or key into N, is Write Buffering, Batching, Coalescing, Sharded Counters.
// Package sharded compares one hot atomic counter with a sharded counter
// whose shards are padded to separate cache lines (no false sharing).
package sharded
import (
"runtime"
"sync/atomic"
)
// cacheLine is 64 bytes on amd64 and most arm64 cores; Apple M-series
// and some others use 128. Padding to 128 is safe on both.
const cacheLine = 128
// shard keeps its counter alone on a cache line.
type shard struct {
n atomic.Int64
_ [cacheLine - 8]byte // padding: the next shard starts on a new line
}
// unpaddedShard is the false-sharing version for the benchmark.
type unpaddedShard struct {
n atomic.Int64
}
// Counter spreads increments over shards; Sum adds them up. Writes scale,
// reads cost O(shards) and are not a point-in-time snapshot.
type Counter struct {
shards []shard
}
// New makes one shard per P (GOMAXPROCS).
func New() *Counter {
return &Counter{shards: make([]shard, runtime.GOMAXPROCS(0))}
}
// Add increments the shard picked by hint (for example a worker ID).
func (c *Counter) Add(hint int, delta int64) {
c.shards[hint%len(c.shards)].n.Add(delta)
}
// Sum reads every shard. Concurrent Adds may or may not be included.
func (c *Counter) Sum() int64 {
var s int64
for i := range c.shards {
s += c.shards[i].n.Load()
}
return s
}
// Unpadded is the same counter with shards packed side by side.
type Unpadded struct {
shards []unpaddedShard
}
// NewUnpadded makes one packed shard per P.
func NewUnpadded() *Unpadded {
return &Unpadded{shards: make([]unpaddedShard, runtime.GOMAXPROCS(0))}
}
// Add increments a packed shard; neighbours share a cache line.
func (c *Unpadded) Add(hint int, delta int64) {
c.shards[hint%len(c.shards)].n.Add(delta)
}golang.org/x/sync: errgroup, SetLimit, semaphore.Weighted, singleflight Important
In plain words: three small packages maintained by the Go team outside the standard library. errgroup is a WaitGroup that returns the first error, can cancel the rest through a context and can limit how many run at once. semaphore.Weighted admits work by size. singleflight lets concurrent callers asking for the same key share one call.
Common misunderstanding: "errgroup collects all errors." Wait "returns the first non-nil error (if any)"; the others are dropped. If you need all of them, collect them yourself (for example into a slice by index and errors.Join).
Definition (from go doc, x/sync v0.19.0):
| API | Doc wording | Note |
|---|---|---|
errgroup.WithContext(ctx) | "The derived Context is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns" | Workers must watch ctx |
(*Group).SetLimit(n) | "limits the number of active goroutines in this group to at most n" | Go blocks while at the limit |
(*Group).TryGo(f) | starts f "only if the number of active goroutines ... is currently below the configured limit" | Non-blocking admission |
semaphore.NewWeighted(n) | "maximum combined weight for concurrent access" | Waiters queue in a FIFO list (source) |
(*Weighted).Acquire(ctx, n) | "blocking until resources are available or ctx is done" | Returns ctx.Err() and acquires nothing on failure |
singleflight.(*Group).Do(key, fn) | "only one execution is in-flight for a given key at a time" | shared reports a collapsed call |
(*Group).Forget(key) | future calls "will call the function rather than waiting" | Use after an error you do not want shared |
req A (key user:42) req B (key user:42) req C (key user:42) DB
1 Do -> miss, calls load query
2 Do -> joins in-flight
3 Do -> joins in-flight
4 load returns v gets v (shared=true) gets v (shared=true) 1 query, not 3The errgroup bounded fan-out is the core of Worker Pools, Pipelines, Fan-Out/Fan-In, which owns pool design; this page shows the API. Singleflight is one half of stampede protection; the cache side is in Caching.
// Package xsync uses golang.org/x/sync: errgroup with a concurrency
// limit, a weighted semaphore, and singleflight to collapse duplicate
// cache misses.
package xsync
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
)
// FetchAll calls fetch for every id with at most limit in flight. The
// first error cancels ctx for the others and is returned by Wait.
func FetchAll(ctx context.Context, ids []int, limit int,
fetch func(context.Context, int) (string, error)) ([]string, error) {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(limit) // Go blocks while limit goroutines are active
out := make([]string, len(ids))
for i, id := range ids {
g.Go(func() error {
v, err := fetch(ctx, id)
if err != nil {
return fmt.Errorf("fetch %d: %w", id, err)
}
out[i] = v // own index: no lock
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return out, nil
}
// MemoryBudget admits jobs by size: a 3-unit job needs 3 free units.
type MemoryBudget struct {
sem *semaphore.Weighted
}
// NewMemoryBudget allows total units in use at once.
func NewMemoryBudget(total int64) *MemoryBudget {
return &MemoryBudget{sem: semaphore.NewWeighted(total)}
}
// Run waits for size units (or ctx), runs job, then releases them.
func (b *MemoryBudget) Run(ctx context.Context, size int64, job func()) error {
if err := b.sem.Acquire(ctx, size); err != nil {
return err // ctx.Err(); nothing was acquired
}
defer b.sem.Release(size)
job()
return nil
}
// TryRun runs job only if size units are free right now.
func (b *MemoryBudget) TryRun(size int64, job func()) bool {
if !b.sem.TryAcquire(size) {
return false
}
defer b.sem.Release(size)
job()
return true
}
// Loader collapses concurrent loads of the same key into one call.
type Loader struct {
g singleflight.Group
load func(key string) (string, error)
}
// NewLoader wraps a slow load function (database, HTTP).
func NewLoader(load func(string) (string, error)) *Loader {
return &Loader{load: load}
}
// Get returns the value; shared is true when other callers got the same
// result from one in-flight call.
func (l *Loader) Get(key string) (string, bool, error) {
v, err, shared := l.g.Do(key, func() (any, error) {
return l.load(key)
})
if err != nil {
return "", shared, err
}
return v.(string), shared, nil
}The race detector on these primitives Must-know
In plain words: go test -race instruments every memory access and reports two accesses from different goroutines, at least one a write, with no happens-before edge between them. Every primitive on this page tells the detector about its edges, so correct code stays quiet.
Common misunderstanding: "No race report means no race." The detector finds races that actually happen during the run. Code paths your tests do not execute concurrently are not checked. Run concurrency tests with -race and enough goroutines to overlap.
Definition: enable with -race on go test, go run, go build or go install; options through GORACE (for example GORACE="halt_on_error=1"). A run with a race exits with status 66. Real report for two goroutines doing n++:
==================
WARNING: DATA RACE
Read at 0x00c00019c038 by goroutine 7:
main.main.func1()
.../lab/race/main.go:15 +0x68
Previous write at 0x00c00019c038 by goroutine 6:
main.main.func1()
.../lab/race/main.go:15 +0x78
Goroutine 7 (running) created at:
main.main()
.../lab/race/main.go:13 +0x6c
==================
2
Found 1 data race(s)
exit status 66| What you wrote | Race detector says | Why |
|---|---|---|
n++ from two goroutines | DATA RACE | No edge |
mu.Lock(); n++; mu.Unlock() | Quiet | Unlock -> Lock edge |
hits.Add(1) | Quiet | Atomic |
Write in worker, read after wg.Wait() | Quiet | Done -> Wait edge |
Read result after a failed TryLock | DATA RACE (if racing) | No edge on failure |
Mixed atomic.AddInt64(&x) and plain x read | DATA RACE | Every access must be atomic |
Mutex profiles: SetMutexProfileFraction Important
In plain words: a mutex profile records where goroutines waited for locks and for how long, attributed to the code that held the lock when it released it. It answers "which lock makes us slow?".
Common misunderstanding: "The CPU profile shows lock contention." Waiting goroutines are parked and use no CPU, so they are invisible there. The diagnostics guide: "Mutex profile reports the lock contentions. When you think your CPU is not fully utilized due to a mutex contention, use this profile. Mutex profile is not enabled by default, see runtime.SetMutexProfileFraction to enable it."
Definition: runtime.SetMutexProfileFraction(rate) reports "on average 1/rate events"; 0 turns it off, a negative rate only reads the current value. Read it with go test -mutexprofile=mutex.out, with pprof.Lookup("mutex"), or over HTTP at /debug/pprof/mutex from net/http/pprof. The related block profile (runtime.SetBlockProfileRate) covers channel and select waits as well. Real output from this page's profile test:
$ go test -run Contention -mutexprofile=mutex.out -o profile.test ./profile
$ go tool pprof -top profile.test mutex.out
Type: delay
Showing nodes accounting for 108.79ms, 100% of 108.79ms total
flat flat% sum% cum cum%
108.79ms 100% 100% 108.79ms 100% sync.(*Mutex).Unlock (inline)
0 0% 100% 108.79ms 100% academy/sync-primitives/profile.TestMutexProfileRecordsContention.func1// Package profile turns on the mutex contention profile and reads it.
package profile
import (
"bytes"
"runtime"
"runtime/pprof"
)
// EnableMutexProfile records on average 1/rate contention events and
// returns the previous rate. rate 1 records every event (tests, short
// investigations); production services usually pick 5 to 100.
func EnableMutexProfile(rate int) (previous int) {
return runtime.SetMutexProfileFraction(rate)
}
// MutexProfileText returns the profile in the human-readable debug=1 form.
// Over HTTP the same data is served by net/http/pprof at
// /debug/pprof/mutex.
func MutexProfileText() (string, error) {
var b bytes.Buffer
if err := pprof.Lookup("mutex").WriteTo(&b, 1); err != nil {
return "", err
}
return b.String(), nil
}Mechanics
Exact messages and what they mean Must-know
| Message (verbatim) | Kind | Recoverable? | Cause |
|---|---|---|---|
fatal error: all goroutines are asleep - deadlock! | Runtime fatal | No | Every goroutine blocked (double Lock, recursive RLock, Wait forever) |
fatal error: sync: unlock of unlocked mutex | Runtime fatal | No | Unlock on an unlocked Mutex |
fatal error: sync: Unlock of unlocked RWMutex | Runtime fatal | No | Same for the write side |
fatal error: sync: RUnlock of unlocked RWMutex | Runtime fatal | No | More RUnlock than RLock |
panic: sync: negative WaitGroup counter | Panic | Yes | Extra Done |
panic: sync: WaitGroup misuse: Add called concurrently with Wait | Panic | Yes | Add from zero racing Wait |
panic: sync: WaitGroup is reused before previous Wait has returned | Panic | Yes | New round too early |
fatal error: concurrent map writes | Runtime fatal | No | Plain map written concurrently |
fatal error: concurrent map read and map write | Runtime fatal | No | Plain map read during a write |
panic: sync/atomic: store of inconsistently typed value into Value | Panic | Yes | atomic.Value given a second type |
panic: sync/atomic: store of nil value into Value | Panic | Yes | Value.Store(nil) |
WARNING: DATA RACE + exit status 66 | Race detector | n/a | Unsynchronised conflicting access |
passes lock by value, copies lock value | go vet copylocks | n/a | Copied a sync value |
WaitGroup.Add called from inside new goroutine | go vet waitgroup (1.25) | n/a | Add in the wrong place |
The fatal errors are thrown by the runtime and cannot be caught with recover: a built binary exits with status 2 and a goroutine dump (go run itself reports exit status 1).
Inside sync.Mutex Good to know
The mutex is one int32 state word and one semaphore. The low bits are flags (mutexLocked, mutexWoken, mutexStarving), the rest counts waiters. The fast path is a single CAS from 0 to locked, and it is inlined into your code. The slow path spins briefly on multicore machines when the mutex is locked in normal mode and the runtime says spinning makes sense, then parks the goroutine on the semaphore. Unlock is an atomic add; if waiters exist it wakes one (normal mode) or hands ownership directly (starvation mode). In current sources the implementation lives in internal/sync/mutex.go and sync.Mutex wraps it with a noCopy marker for vet.
state int32: [ waiter count ... | starving | woken | locked ]
Lock fast: CAS(state, 0, locked) -> done, no syscalls
Lock slow: spin (normal mode only) -> add waiter -> semacquire (park)
Unlock fast: add(state, -locked) == 0 -> done
Unlock slow: wake one waiter, or hand off when starvingInside sync.Pool Good to know
Each P has a poolLocal with a private slot (only that P uses it, no atomics) and a shared lock-free chain the owner pushes and pops at the head and other Ps steal from the tail. Get tries private, then own shared, then steals from other Ps, then the victim cache, then New. poolCleanup runs "with the world stopped, at the beginning of a garbage collection": it drops the victims and turns every primary cache into the new victim.
Knobs and tools you will use Must-know
| Knob / command | Effect |
|---|---|
go test -race ./... | Race detector on all tests |
GORACE="halt_on_error=1 log_path=race" | Stop at first race; write reports to files |
go vet ./... | copylocks, waitgroup (1.25), atomic misuse (atomic analyzer: x = atomic.AddInt64(&x, 1)) |
runtime.SetMutexProfileFraction(n) | Sample 1/n contention events |
runtime.SetBlockProfileRate(ns) | Sample blocking events (channels, select, locks) |
go test -mutexprofile=m.out -blockprofile=b.out | Write profiles from tests |
/debug/pprof/mutex, /debug/pprof/block | Same over HTTP via net/http/pprof |
GOMAXPROCS | Number of Ps: shard count for per-P structures, parallelism of contention |
b.RunParallel | Benchmark with GOMAXPROCS goroutines to measure contention |
kill -QUIT pid / GOTRACEBACK=all | Dump all goroutines of a hung process to find who holds what |
Solving the classic problems
Problem: a counter loses increments under load
| Solution | How | Advantage | Cost |
|---|---|---|---|
atomic.Int64 | hits.Add(1) | Simplest, no lock | One hot cache line |
| Mutex | lock around n++ | Can update related fields together | Slower, contention |
| Sharded counter | per-P padded shards, sum on read | Scales with cores | Memory, read cost, no snapshot |
| Batch then flush | local count per worker, add every N | Fewest shared writes | Delayed visibility |
When the counter must survive restarts, batch in memory and flush with one SQL statement per interval instead of one per request:
-- flush a sharded in-memory counter every second: one row update, not one per request
UPDATE page_views SET views = views + $1 WHERE page_id = $2;
-- while debugging contention on the database side instead of in Go:
SELECT pid, wait_event_type, wait_event, state, left(query, 60)
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';Problem: a check-then-act race on a balance
The bug is if a.Balance() >= x { a.Withdraw(x) } with two separately locked calls. Fix: one method that checks and updates under one lock (Withdraw in the account snippet). Across processes or replicas, an in-memory lock does nothing; use the database (UPDATE ... SET balance = balance - $1 WHERE id = $2 AND balance >= $1), see Optimistic vs Pessimistic Locking.
Problem: cache stampede on a cold key
| Solution | How | Advantage | Cost |
|---|---|---|---|
singleflight.Group | g.Do(key, load) | One load per key per process | Per-process only; a slow load blocks all joiners |
RWMutex + re-check | GetOrLoad in the rwcache snippet | No dependency | Load runs under the write lock |
sync.Map.LoadOrStore | build, then keep the first | Lock-free reads | Duplicate builds possible |
| Distributed lock / request coalescing at the cache | Redis SET NX | Across replicas | Network, lease expiry (Distributed Locking) |
Problem: hot-reload config without stopping readers
Use atomic.Pointer[Config]: build a complete new Config, then Store. Readers call Load once per request and use that snapshot. Never mutate a published Config; treat it as immutable. If two reloaders can race, guard them with a Mutex.
Problem: unbounded fan-out exhausts connections
Use errgroup.SetLimit(n) for "at most n at once" or semaphore.Weighted when tasks have different costs (a 3 MB image takes 3 units of a 64-unit memory budget). Pair the limit with the size of the downstream pool (db.SetMaxOpenConns): a limit above it only moves the queue into the pool.
Problem: two transfers deadlock
Lock in a fixed order (by ID) as in Transfer. If accounts can be the same, handle from == to first. If ordering is impossible (locks discovered as you go), take the first with Lock and the rest with TryLock, releasing everything and retrying with backoff on failure; this is one of the rare legitimate TryLock uses.
Problem: allocation churn in a hot path
Profile first (-benchmem, heap profile). If short-lived buffers dominate, pool *bytes.Buffer with a size cap, reset on Get, never use after Put. If the object is small or the path is not hot, the pool costs more than it saves.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Pass work or results between goroutines | Channel | select with ctx.Done() | Ownership moves; no shared state |
| One counter or flag | atomic.Int64 / atomic.Bool | Sharding if it is the top of a profile | One word, no invariant |
| Several fields that must change together | sync.Mutex | Named field, defer Unlock | Invariants span fields |
| Read-mostly, reads do real work | sync.RWMutex | Benchmark against Mutex | Parallel readers |
| Read-mostly, rarely changes, many fields | atomic.Pointer[T] copy-on-write | Mutex for writers | Readers never block |
| Grow-only cache, disjoint keys | sync.Map | Generic wrapper | Designed for exactly this |
| One-time setup | sync.OnceValue(s) / Once | Store the error | Correct double-checked locking |
| Wait for N goroutines | WaitGroup.Go (1.25) or Add before go | errgroup if they can fail | Simple join |
| Bounded parallel work that can fail | errgroup + SetLimit | WithContext | First error cancels the rest |
| Weighted admission | semaphore.Weighted | Acquire(ctx, n) | Different costs per task |
| Duplicate concurrent loads | singleflight | Forget on errors | One call per key |
| Wait for a complex condition on shared state | sync.Cond | Loop around Wait | Channels cannot express it cleanly |
| Reuse expensive temporary buffers | sync.Pool | Cap size, reset | Lower GC pressure |
| State shared across processes or machines | Not sync | Database row locks, Redis lock, leader election | In-process locks do not cross process boundaries |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Everything on this page works here and only here: a Mutex protects memory inside one process. A typical Go monolith has a handful of package-level singletons built with sync.OnceValues (database pool, template set), atomics for metrics, errgroup in request handlers that call two or three dependencies in parallel, and a Mutex around any in-memory cache. The simplest correct rule: no package-level mutable variable without a named guard. The database still owns correctness of persistent data: a Go mutex around "read balance, write balance" is wrong as soon as a second instance runs, so use row locks or atomic SQL updates.
Modular monolith and multiple databases
Each module owns its locks; a module never locks another module's mutex. The lock hierarchy follows the dependency direction: a higher layer may call into a lower one while holding its lock only if the lower one never calls back up. Callbacks across modules (event handlers, hooks) must run outside any lock, or you build cross-module deadlocks no single team can see. A shared sync.Pool of buffers across modules is fine; shared mutable maps are not.
Microservices
Nothing in sync crosses a service boundary. What survives is the pattern: errgroup with SetLimit per downstream service (a bulkhead, see Bulkheads & Graceful Degradation), singleflight in front of a slow dependency, and atomic.Pointer for config pushed from a control plane. A typical flow: the order service receives a request, errgroup.WithContext calls inventory and pricing in parallel, the first failure cancels the other through the context, and the response is assembled after Wait. Mutual exclusion between instances becomes a database lock, a Redis lease or Leader Election.
Distributed data: replicas, caches, sharded and multi-region
In-process caches in front of replicas need two things from this page: a lock or sync.Map for the cache itself and singleflight so a cache miss does not send N identical queries to the primary. Invalidation messages arrive on another goroutine, so the cache's map must be written under its lock or swapped with atomic.Pointer. Each instance has its own cache and its own singleflight; across instances you still get one load per instance, which is usually acceptable. Exactly-once across instances is not a sync problem: use idempotency keys and database constraints.
Scaling path: 1x, 10x, 100x
At 1x a single Mutex around a struct is correct and fast enough. At 10x the mutex profile shows the hot lock: shorten the critical section, move I/O out, switch counters to atomics, consider RWMutex only after a benchmark. At 100x the shared variable itself is the bottleneck: shard it per P or per key range, pad hot fields to cache lines, switch read-mostly state to copy-on-write with atomic.Pointer, and batch writes to the database. Past one machine the same move happens at system level: sharded counters and partitioned ownership replace locks.
Lab
All outputs below were produced on the author's machine (Go 1.27.4, darwin/arm64, Apple M4 Pro); the module declares go 1.24.0. The first block runs the snippet module; the lab folder holds the deliberately broken programs used for the error outputs above (they are not in the snippet module because vet must stay clean there).
- Run every test with the race detector.
$ cd docs/snippets/go/sync-primitives/go
$ go vet ./... && go test -race -count=1 ./...
ok academy/sync-primitives/atomics 1.337s
ok academy/sync-primitives/cond 1.326s
ok academy/sync-primitives/mutex 1.396s
ok academy/sync-primitives/once 1.326s
ok academy/sync-primitives/pool 1.326s
ok academy/sync-primitives/profile 1.346s
ok academy/sync-primitives/rwcache 1.317s
ok academy/sync-primitives/sharded 1.316s
ok academy/sync-primitives/syncmap 1.306s
ok academy/sync-primitives/waitgroup 1.297s
ok academy/sync-primitives/xsync 1.355s- Compare
RWMutexwithMutex, pooled with unpooled rendering, and the three counters (numbers vary by machine; the ratios are the point).
$ go test -run XXX -bench . -benchtime=200ms ./rwcache ./pool ./sharded
BenchmarkReadRWMutex-12 1864264 126.7 ns/op
BenchmarkReadMutex-12 2384200 98.92 ns/op
BenchmarkRenderPool-12 1110426 220.6 ns/op 144 B/op 7 allocs/op
BenchmarkRenderNoPool-12 1000000 231.4 ns/op 256 B/op 9 allocs/op
BenchmarkSingleAtomic-12 3965660 53.37 ns/op
BenchmarkShardedPadded-12 1000000000 0.1786 ns/op
BenchmarkShardedUnpadded-12 6407924 32.55 ns/opMake a race and watch the detector: write
n++in two goroutines (the program in The race detector) and rungo run -race .; expectWARNING: DATA RACEandexit status 66. Replacen++with anatomic.Int64and the report disappears.Lock a mutex twice in
mainand run it:fatal error: all goroutines are asleep - deadlock!withgoroutine 1 [sync.Mutex.Lock]. Then callUnlockon a fresh mutex:fatal error: sync: unlock of unlocked mutex.Write a plain map from eight goroutines without a lock:
fatal error: concurrent map writes. Then change it to thesyncmap.Mapwrapper or amapplusMutex.Add a value receiver to a struct with a mutex and run
go vet:passes lock by value. Movewg.Add(1)inside the goroutine and rungo vet:WaitGroup.Add called from inside new goroutine.Collect a mutex profile from the profile test and read it with
go tool pprof -top(output in Mutex profiles).
Common misconceptions
| Belief | Reality |
|---|---|
| A goroutine can re-lock a mutex it holds | Go mutexes are not reentrant; the second Lock blocks forever |
| Only the locking goroutine may unlock | Any goroutine may; there is no owner |
RWMutex is always faster for reads | Each RLock writes a shared counter; for tiny sections Mutex often wins |
| A read lock can be upgraded | No upgrade or downgrade; release and re-check |
Cond.Wait can wake spuriously in Go | It cannot; the loop is needed because another goroutine may change the state first |
wg.Add(1) inside the goroutine is fine | Wait can return before it runs; vet (1.25) reports it |
Once retries if the function failed | Never; a panic also counts as done |
sync.Pool is a connection pool | The GC may drop items at any time; only for disposable objects |
sync.Map is the default concurrent map | Specialised; map plus Mutex is the default |
Atomics are relaxed, like C++ memory_order_relaxed | All Go atomics are sequentially consistent |
| Two atomic updates form one consistent change | Each is atomic alone; use a Mutex for multi-field invariants |
| The runtime detects every deadlock | Only when all goroutines are blocked; a server just hangs |
| No race report means race-free | Only executed interleavings are checked |
| A Go mutex protects data across instances | It is in-process memory; use database or distributed locks |
Cheat sheet
| Topic | Remember |
|---|---|
| Mutex shape | mu sync.Mutex named field next to guarded fields; Lock(); defer Unlock() |
| Never copy | Pointer receivers; go vet copylocks |
| Reentrancy | None; split into fooLocked helpers |
TryLock | Rare; failed call has no memory effect |
| Fairness | Normal mode unfair and fast; starvation mode after 1 ms waits, FIFO hand-off |
| RWMutex | Writer preference; no recursive RLock; no upgrade; benchmark first |
| WaitGroup | Add before go or wg.Go (1.25); defer Done; pass by pointer |
| Once | OnceValue(s) for lazy singletons; errors and panics are cached |
| Cond | Hold L; for !cond { Wait() }; usually use channels |
| Pool | Store pointers, Reset on Get, cap sizes, GC may clear it |
| sync.Map | Grow-only or disjoint keys; wrap for types; Range not a snapshot |
| Atomics | Typed values (atomic.Int64, Bool, Pointer[T]); sequentially consistent |
| CAS loop | Load, compute, CompareAndSwap, retry |
| Deadlocks | Global lock order; no blocking calls under a lock |
| False sharing | Pad hot per-core data to a cache line (64 or 128 bytes) |
| x/sync | errgroup.SetLimit, semaphore.Weighted, singleflight.Do |
| Diagnose | -race, go vet, SetMutexProfileFraction, /debug/pprof/mutex |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A method holding c.mu calls c.Len(), which also locks c.mu. What happens and how do you fix it? Must-know
Answer
Answer: It blocks forever: Go mutexes are not reentrant. If it is the only goroutine, the runtime prints fatal error: all goroutines are asleep - deadlock!. Fix: have an unexported lenLocked() that assumes the lock is held, and call that.
2 — Why does go vet complain about func (c Counter) Get() int when Counter has a sync.Mutex? Must-know
Answer
Answer: The value receiver copies the mutex, so Get locks a private copy and protects nothing (copylocks: "passes lock by value"). Use a pointer receiver.
3 — Readers hold an RWMutex and a writer is waiting. A reader calls RLock again. What happens? Good to know
Answer
Answer: The second RLock blocks behind the pending writer, and the writer waits for the first read lock: deadlock. The doc says this "prohibits recursive read-locking".
4 — Why must wg.Add(1) come before the go statement? Must-know
Answer
Answer: If Wait runs while the counter is still zero, it returns immediately. A positive Add from zero must happen before Wait. wg.Go (Go 1.25) does this for you.
5 — sync.OnceValues(load) returned an error the first time. What happens on the second call? Important
Answer
Answer: It returns the same error; load is not called again. If you need retry, use a mutex with your own "loaded" flag, or reset by replacing the whole once value.
6 — Go's Cond.Wait cannot wake spuriously. Why is the for loop still required? Important
Answer
Answer: Between Signal and re-acquiring the lock another goroutine may take the item or change the state, so the condition may be false again when Wait returns.
7 — Name two mistakes that make sync.Pool slower or wrong. Important
Answer
Answer: Storing a non-pointer value like []byte (allocates on every Put), not resetting the object on Get, keeping huge buffers, using an object after Put, or relying on items to persist across GC cycles.
8 — When is sync.Map the right choice? Important
Answer
Answer: When keys are written once and read many times (grow-only caches) or goroutines work on disjoint key sets. Otherwise a plain map with a Mutex is clearer and usually as fast.
9 — Two goroutines update minLatency and maxLatency with two separate atomics. A reader sees min greater than max. Why? Important
Answer
Answer: Each atomic is consistent alone, but the pair is not updated as one unit; the reader can see one new and one old value. Use a mutex or publish both in one immutable struct via atomic.Pointer.
10 — Why can padding a struct field to 128 bytes make a counter faster? Important
Answer
Answer: It puts each shard on its own cache line, so cores do not invalidate each other's lines on every write (false sharing).
11 — CPU usage is 30% but latency is high under load. Which profile do you turn on? Important
Answer
Answer: The mutex profile (runtime.SetMutexProfileFraction) and possibly the block profile. Parked goroutines do not show in a CPU profile.
12 — What does errgroup.Wait return when three tasks fail? Must-know
Answer
Answer: The first non-nil error only. With WithContext, that first failure also cancels the context the others receive.
Glossary
| Term | Meaning |
|---|---|
| Critical section | Code that only one goroutine may run at a time, between Lock and Unlock |
sync.Mutex | Mutual exclusion lock; zero value unlocked; not reentrant |
Lock / Unlock | Acquire and release a mutex |
TryLock | Acquire only if free; returns false otherwise (Go 1.18) |
| Reentrant mutex | A lock the same owner can take again; Go has none |
| Lock scope | The span of code that holds the lock; keep it short |
| copylocks | go vet analyzer that reports copied sync values |
noCopy | Zero-size marker type vet uses to detect copies |
| Embedding mutex | Putting sync.Mutex as an anonymous field; leaks Lock into the API |
| Contention | Goroutines waiting for the same lock |
| Normal mode | Mutex mode where new arrivals can barge ahead of woken waiters |
| Starvation mode | Mutex mode with direct FIFO hand-off after a waiter waits more than 1 ms |
| Spinning | Busy-waiting briefly before parking, on multicore machines |
sync.RWMutex | Reader/writer lock: many readers or one writer |
RLock / RUnlock | Acquire and release the shared (read) side |
| Writer preference | A waiting writer blocks new readers so it cannot starve |
| Lock upgrade | Turning a read lock into a write lock; not supported |
sync.WaitGroup | Counter of outstanding tasks; Wait blocks until zero |
Add / Done / Wait | Raise, lower by one, and wait for zero on a WaitGroup |
WaitGroup.Go | Go 1.25 method: Add(1), start f, Done when it returns |
sync.Once | Runs a function exactly once; others wait for it |
OnceFunc / OnceValue / OnceValues | Go 1.21 helpers returning once-only functions |
| Lazy initialization | Building a value on first use instead of at start-up |
sync.Cond | Condition variable tied to a Locker |
Wait (Cond) | Unlock, sleep until signalled, relock |
Signal / Broadcast | Wake one / all goroutines waiting on a Cond |
| Spurious wakeup | Waking without a signal; possible in POSIX, not in Go's Cond |
sync.Pool | Per-P cache of reusable objects that the GC may clear |
Get / Put | Take an object from / return it to a pool |
| GC-cleared | Pool contents are dropped across garbage collections |
| Victim cache | Second-chance pool cache that survives one GC (Go 1.13) |
| Buffer reuse | Recycling *bytes.Buffer values to cut allocations |
sync.Map | Concurrent map optimised for grow-only and disjoint-key use |
Load / Store / LoadOrStore / Range | sync.Map read, write, insert-if-absent and iteration |
sync/atomic | Package of indivisible memory operations |
atomic.Int64 | Typed 64-bit atomic integer, auto-aligned (Go 1.19) |
atomic.Bool | Typed atomic boolean |
atomic.Pointer[T] | Typed atomic pointer for copy-on-write publication |
atomic.Value | Atomic holder of any value of one concrete type |
Add / Load / Store / Swap | Atomic increment, read, write and exchange |
CompareAndSwap (CAS) | Replace only if the current value equals the expected one |
| Lock-free | Progress through atomic retries rather than blocking on locks |
| ABA problem | CAS succeeds although the value changed and changed back |
| Sequentially consistent | All atomics appear in one global order consistent with each goroutine |
| Happens-before | Ordering that guarantees a write is visible to a read |
| Synchronizes before | The memory model's name for a cross-goroutine edge |
| Data race | Concurrent accesses to one variable, at least one a write, with no happens-before |
| Deadlock | Goroutines waiting on each other forever |
| Lock ordering | Always acquiring multiple locks in one global order |
| Lock hierarchy | Layered order: hold a higher-level lock, take only lower-level ones |
| False sharing | Independent variables on one cache line slowing each other |
| Cache line | Unit of memory moved between caches (64 or 128 bytes) |
| Padding | Unused bytes that push data onto separate cache lines |
| Sharded counter | N independent counters summed on read |
errgroup | x/sync group with first error and context cancellation |
SetLimit | Caps active goroutines in an errgroup |
semaphore.Weighted | x/sync semaphore where each acquire takes n units |
singleflight | x/sync duplicate call suppression per key |
| Race detector | -race instrumentation that reports data races at run time |
| Mutex profile | pprof profile of lock contention delay |
SetMutexProfileFraction | Sets the sampling rate of the mutex profile |
| Block profile | pprof profile of all blocking (channels, select, locks) |
flock | OS advisory file lock; PHP's cross-process lock primitive |
| APCu | PHP shared-memory user cache within one FPM pool |
For PHP/Laravel developers
PHP-FPM gives every request its own process (or worker) with its own memory. There is nothing to share, so there is nothing to lock in memory: no Mutex, no data races on variables, no sync.Map. A Go server is one process where every request is a goroutine in the same address space; a package-level map is shared by every request at once. That is why Go needs this page and PHP mostly does not.
| Need | PHP / Laravel | Go |
|---|---|---|
| Mutual exclusion on one machine | flock($fp, LOCK_EX) on a file | sync.Mutex (in-process) |
| Mutual exclusion across servers | Cache::lock('key', 10)->get(...) (Redis/database) | Same idea: database row lock or Redis lease; not sync |
| Shared in-memory cache | APCu (apcu_fetch, apcu_store), per FPM pool | sync.Map, map + Mutex, atomic.Pointer |
| Run once per process | Static property / service container singleton | sync.OnceValue |
| Wait for parallel work | Http::pool, queued jobs, Bus::batch | WaitGroup, errgroup |
| Counter | Redis::incr('hits') or apcu_inc | atomic.Int64 (plus a periodic flush) |
<?php
// Cross-process mutual exclusion in PHP: an advisory file lock.
$fp = fopen('/tmp/report.lock', 'c');
if (flock($fp, LOCK_EX | LOCK_NB)) { // like TryLock
try {
buildReport();
} finally {
flock($fp, LOCK_UN);
fclose($fp);
}
}
// Across servers in Laravel: an atomic cache lock (Redis, database, memcached drivers).
Cache::lock('report', 10)->get(function () {
buildReport();
});When you port PHP code to Go, the first review question for every package-level variable is "which goroutines touch this, and what guards it?". Laravel's Cache::lock maps to Distributed Locking, not to sync.Mutex.
References
- The Go Memory Model (version of June 6, 2022): https://go.dev/ref/mem
syncpackage source and doc comments: https://go.dev/src/sync/mutex.go, https://go.dev/src/sync/rwmutex.go, https://go.dev/src/sync/waitgroup.go, https://go.dev/src/sync/once.go, https://go.dev/src/sync/oncefunc.go, https://go.dev/src/sync/cond.go, https://go.dev/src/sync/pool.go, https://go.dev/src/sync/map.go- Mutex fairness comment (normal and starvation modes): https://go.dev/src/internal/sync/mutex.go
sync/atomicdoc, typed values andValuepanics: https://go.dev/src/sync/atomic/doc.go, https://go.dev/src/sync/atomic/type.go, https://go.dev/src/sync/atomic/value.go- Effective Go, "Share by communicating": https://go.dev/doc/effective_go
- Go FAQ, "Why are map operations not defined to be atomic?": https://go.dev/doc/faq
- Go Code Review Comments, "Copying": https://go.dev/wiki/CodeReviewComments
- Diagnostics (mutex and block profiles): https://go.dev/doc/diagnostics
- Data Race Detector: https://go.dev/doc/articles/race_detector
- Introducing the Go Race Detector (Go blog): https://go.dev/blog/race-detector
- Share Memory By Communicating (Go blog codewalk): https://go.dev/blog/codelab-share
- Go Concurrency Patterns: Pipelines and cancellation (Go blog): https://go.dev/blog/pipelines
- The Go Programming Language Specification: https://go.dev/ref/spec
- Release notes: https://go.dev/doc/go1.3 (Pool), https://go.dev/doc/go1.14 (defer cost), https://go.dev/doc/go1.4 (atomic.Value), https://go.dev/doc/go1.9 (sync.Map, fairness), https://go.dev/blog/go1.9, https://go.dev/doc/go1.13 (Pool victim cache), https://go.dev/doc/go1.18 (TryLock), https://go.dev/doc/go1.19 (memory model, typed atomics), https://go.dev/doc/go1.20, https://go.dev/doc/go1.21 (OnceFunc), https://go.dev/doc/go1.23 (And/Or, Map.Clear), https://go.dev/doc/go1.24 (sync.Map rewrite), https://go.dev/doc/go1.25 (WaitGroup.Go, vet waitgroup)
golang.org/x/syncv0.19.0 (errgroup,semaphore,singleflight), read withgo docfrom the module cache; source: https://go.googlesource.com/sync