Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why Go has both channels and locksWhy it exists
Which Go version added whatWhere it comes from
Lock, Unlock, defer, lock scope, reentrancysync.Mutex
passes lock by value, embedding a mutexCopying a lock
TryLockTryLock
Fairness, starvation mode, spinningContention and starvation mode
RLock, writer preference, upgradesync.RWMutex
Add before go, wg.Go, reusesync.WaitGroup
Lazy initialisation, OnceValuesync.Once and friends
Wait/Signal/Broadcast, spurious wakeupssync.Cond
Buffer reuse, GC clearingsync.Pool
Concurrent map, LoadOrStoresync.Map
atomic.Int64, atomic.Pointer[T]Atomic values
CAS loops, lock-free codeCompare-and-swap
Happens-before per primitiveThe memory model
Lock ordering, lock hierarchyDeadlocks with locks
Cache lines, padding, sharded countersFalse sharing
errgroup, semaphore, singleflightgolang.org/x/sync
WARNING: DATA RACEThe race detector
SetMutexProfileFractionMutex profiles
Exact fatal errors and panicsMechanics
Mutex or channel or atomicChoosing
flock, Redis locks, APCuFor PHP/Laravel developers
Reproduce the outputsLab

Everything in one minute ​

The primitives.

TypeIn plain wordsTiny exampleUse it for
sync.MutexOne goroutine at a timemu.Lock(); defer mu.Unlock()Several fields that change together
sync.RWMutexMany readers or one writermu.RLock(); defer mu.RUnlock()Read-mostly state with real work under the lock
sync.WaitGroupCount tasks, wait for zerowg.Go(f); wg.Wait()Wait for N goroutines
sync.OnceRun a function exactly onceonce.Do(setup)Lazy initialisation
sync.OnceValue(s)Once that returns the resultcfg := sync.OnceValue(load)Lazy singletons, Go 1.21+
sync.CondSleep until another goroutine says "changed"for !ok() { c.Wait() }Rare; channels usually win
sync.PoolA free list the GC may emptyb := pool.Get().(*bytes.Buffer)Reusing short-lived allocations
sync.MapA map safe for concurrent usem.LoadOrStore(k, v)Grow-only caches, disjoint keys
atomic.Int64 etc.One word updated indivisiblyhits.Add(1)Counters, flags, pointer swaps
errgroup.GroupWaitGroup plus first error plus limitg.SetLimit(8); g.Go(f)Bounded fan-out that can fail
semaphore.WeightedN units, take k at a timesem.Acquire(ctx, 3)Weighted admission (memory, connections)
singleflight.GroupConcurrent identical calls share oneg.Do(key, load)Cache-miss stampedes

The guarantees (memory model, "synchronizes before").

PrimitiveEdge
Mutex/RWMutexUnlock n -> Lock m returns, for n < m; RUnlock -> next Lock
Failed TryLockNo edge at all
WaitGroupDone (or return of a Go function) -> return of the Wait it unblocks
OnceReturn of f -> return of every once.Do(f)
CondSignal/Broadcast -> return of the Wait it unblocks
PoolPut(x) -> the Get that returns x
sync.MapA write -> any read that observes it
sync/atomicA -> B when B observes A; all atomics are sequentially consistent

The failures you will see.

MessageCause
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 mutexUnlock without Lock (often a double Unlock)
panic: sync: negative WaitGroup counterMore Done than Add
fatal error: concurrent map writesPlain map written from two goroutines
WARNING: DATA RACE-race saw unsynchronised conflicting accesses
passes lock by value / assignment copies lock valuego vet copylocks: a struct with a mutex was copied
WaitGroup.Add called from inside new goroutinego 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, coarserFiner, riskier
One Mutex around the whole structRWMutex, sharding, lock-free atomics
Channels: ownership moves, no shared stateShared state with locks: less copying, more discipline
sync.Once / OnceValueHand-rolled double-checked locking with atomics
Plain map + Mutexsync.Map: faster only for two specific access patterns
Allocate freely and let the GC worksync.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 ​

  1. "Go's mutex is like Java's synchronized: I can lock it again in a nested call." No. A sync.Mutex is not reentrant and is not owned by a goroutine; locking it twice in the same goroutine blocks forever (sync.Mutex).
  2. "RWMutex is always faster for reads." Every RLock still writes a shared counter. With a short critical section a plain Mutex is often faster; on the machine that produced this page's numbers, a read-only parallel benchmark measured 126.7 ns/op for RWMutex against 98.9 ns/op for Mutex (sync.RWMutex).
  3. "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 versionWhat arrivedSource
1.0Mutex, RWMutex, WaitGroup, Once, Cond, sync/atomic functionsPackage history
1.3sync.Pool ("an efficient mechanism for implementing certain types of caches")go1.3 notes
1.4atomic.Valuego1.4 notes
1.9sync.Map; "Mutex is now more fair" (starvation mode)go1.9 notes
1.13Pool "retains some objects across GCs" (victim cache)go1.13 notes
1.18Mutex.TryLock, RWMutex.TryLock, RWMutex.TryRLockgo1.18 notes
1.19Memory model revised; typed atomics atomic.Int64, atomic.Pointer[T] and friendsgo1.19 notes
1.21OnceFunc, OnceValue, OnceValuesgo1.21 notes
1.23atomic And/Or; sync.Map.Cleargo1.23 notes
1.24New sync.Map implementation, less contention on disjoint keysgo1.24 notes
1.25WaitGroup.Go; go vet waitgroup analyzergo1.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()                115

Rules that keep it correct.

RuleWhy
Put mu next to the fields it guards, and say so in a commentReaders know which fields need the lock
Use a named, unexported field (mu sync.Mutex), not embeddingEmbedding promotes Lock/Unlock into your public API; callers can lock your object from outside
mu.Lock(); defer mu.Unlock() at the top of short methodsUnlock runs on every return path and on panic
Keep the critical section short: no I/O, no channel send, no callbackHolding a lock while blocking turns one slow call into a queue
Check and act under the same lockif 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 itNot reentrant: self-deadlock
Use pointer receivers on types with a mutexA 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.

go
// 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.344s

Copying 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 pathExampleFix
Value receiverfunc (c Counter) Get() intfunc (c *Counter) Get() int
Pass by valuereport(stats)report(&stats)
Range copyfor _, a := range accounts { a.mu.Lock() }for i := range accounts { accounts[i].mu.Lock() } or []*Account
Map valuemap[string]Accountmap[string]*Account
Embeddingtype 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."

Normal mode (default)mutex freewoken waiter(head of FIFO)new arrivals(on CPU, spinning)Both race for the lock; arrivals usually winHigh throughput, unfair, tail latency riskStarvation mode (Go 1.9+)Unlockhead waiternew arrivalsjoin queue tailhand-offStrict FIFO, no spinning, slower but fairEnter starvation: a waiter has waited more than 1 ms (starvationThresholdNs = 1e6)Leave: the new owner was the last waiter, or it waited less than 1 ms
     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 mode

Contention signs and fixes.

SymptomLikely causeFix
CPU not saturated, latency high under loadGoroutines queue on one mutexMutex profile (Mutex profiles), shorten the critical section
p99 spikes but p50 fineUnfair normal mode, long holdsMove I/O out of the lock; shard the state
Hot counter in a profileEvery request updates one variableAtomic, or a sharded counter (False sharing)
Read-heavy map lock at the top of the profileMany readers serialisedRWMutex 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.

timeR1holds RLockR2holds RLockWLock: waits for readerswritesR3RLock blocks behind pending WreadsW arrivesIf R1 calls RLock again while W waits: R1 waits for W, W waits for R1, deadlock
     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: deadlock

Real 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):

Benchmarkns/op
BenchmarkReadRWMutex-12126.7
BenchmarkReadMutex-1298.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.

go
// 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 goroutine

Definition: 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)
MistakeSymptomFix
Add inside the goroutineWait returns early, results missing, vet warningAdd before go, or wg.Go
Forgot Done on an error pathWait hangs, all goroutines are asleepdefer wg.Done() first line, or wg.Go
Done twicepanic: sync: negative WaitGroup counterOne Done per Add(1)
Passed wg by valueWait never returns (copy counted)Pass *sync.WaitGroup, vet copylocks warns
Reused before Wait returnedsync: WaitGroup is reused before previous Wait has returnedNew round only after Wait
Need the first errorWaitGroup has no error channelerrgroup.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.

go
// 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
//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)
VariantSignatureOn panicTypical use
sync.Onceonce.Do(func())Marked done; later calls skipStruct-scoped init, close-once
sync.OnceFuncfunc(f func()) func()Re-panics every callIdempotent Close, one-time log
sync.OnceValuefunc(f func() T) func() TRe-panics every callLazy table, compiled regexp
sync.OnceValuesfunc(f func() (T, error)) func() (T, error)Re-panics every callLoad config or a client once
package init()runs at program startCrashes the programCheap, 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.

go
// 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
Needsync.CondChannel
Wake one waiterSignalsend one value
Wake all waitersBroadcastclose(ch) (once only)
Timeout or cancel while waitingNot possibleselect with ctx.Done() or a timer
Wait on a complex predicate over shared stateNaturalAwkward
Wake all, many timesBroadcast againNeeds a new channel each time
go
// 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
PitfallWhat happensFix
Not resetting on GetPrevious user's bytes leak into your outputb.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 buffersOne 10 MB request pins 10 MB per P foreverDrop items above a cap before Put
Using the object after PutAnother goroutine is now writing itPut last; copy what you return
Pooling cheap objectsPool overhead exceeds newBenchmark with -benchmem first
Expecting persistenceItems disappear each GCTreat 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.

go
// 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)
OptionType safetyBest forWeak at
map + MutexFullGeneral use, invariants across keysVery high read contention
map + RWMutexFullRead-mostly with non-trivial readsTiny reads (see benchmark)
sync.Mapany (wrap it)Grow-only caches, disjoint key setsFrequent overwrite of shared keys, len
Sharded map + Mutex per shardFullLarge hot mapsCross-shard operations
atomic.Pointer[map[K]V] copy-on-writeFullRarely changing lookup tablesFrequent 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:

go
// 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
TypeMethodsTypical use
atomic.Int64 / Uint64Add, Load, Store, Swap, CompareAndSwap, And, OrRequest counters, IDs, high-water marks
atomic.Int32 / Uint32SameSmall counters, state enums
atomic.BoolLoad, Store, Swap, CompareAndSwapShutdown flag, "already started"
atomic.Pointer[T]Load, Store, Swap, CompareAndSwapCopy-on-write config, routing tables
atomic.ValueLoad, Store, Swap, CompareAndSwapPre-generics code; one concrete type only, Store(nil) panics
Functions atomic.AddInt64(&x, 1)Same operations on plain variablesLegacy 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.

go
// 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
PatternPrimitiveSafe for
CounterAddOne word
One-shot flagBool.CompareAndSwap(false, true)"only one caller wins"
Max/min trackingCAS loop on Int64One word, monotonic
Copy-on-write snapshotPointer[T].Store of a new immutable valueMany fields, readers never lock
Lock-free stack/queueCAS 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.

goroutine Agoroutine Bsynchronizes beforex = 1; mu.Unlock()mu.Lock(); read xout[i] = v; wg.Done()wg.Wait() returnsonce.Do(f): f returnsonce.Do(f) returnscfg := build(); p.Store(cfg)p.Load() sees cfgEvery write before the left edge is visible after the right edge.A failed TryLock creates no edge; plain reads and writes create none either.
     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.Do

The 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 shapeExamplePrevention
Lock-order inversionTwo transfers in opposite directionsOrder by ID (snippet)
Self-deadlockMethod holding mu calls another method that locks muSplit into locked public and unlocked private (fooLocked) methods
Recursive RLockReader calls a helper that RLocks againNever re-enter; pass state down
Lock plus channelHold mu, send on a full channel whose reader needs muNever block on channels under a lock
Once recursiononce.Do(f) where f calls once.DoRestructure init
Wait without DoneEarly return skipped Donedefer 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.

Packed shards: one cache line, two writerscore 0core 1n0n1unusedEach Add invalidates the other core's copy: the line ping-pongs (measured 32.6 ns/op)Padded shards: one cache line per shardcore 0core 1n0_ [120]byten1_ [120]byteEach core keeps its own line in cache (measured 0.18 ns/op, 12 goroutines)Trade-off: 16x more memory per shard; Sum reads every shard and is not a snapshot

Measured on this page's machine (12 goroutines, b.RunParallel):

Benchmarkns/opWhy
BenchmarkSingleAtomic-1253.37One line, every core contends
BenchmarkShardedUnpadded-1232.55Separate counters, shared lines
BenchmarkShardedPadded-120.1786One 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 transfers

golang.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.

go
// 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):

APIDoc wordingNote
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 3

The 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.

go
// 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 wroteRace detector saysWhy
n++ from two goroutinesDATA RACENo edge
mu.Lock(); n++; mu.Unlock()QuietUnlock -> Lock edge
hits.Add(1)QuietAtomic
Write in worker, read after wg.Wait()QuietDone -> Wait edge
Read result after a failed TryLockDATA RACE (if racing)No edge on failure
Mixed atomic.AddInt64(&x) and plain x readDATA RACEEvery 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
go
// 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)KindRecoverable?Cause
fatal error: all goroutines are asleep - deadlock!Runtime fatalNoEvery goroutine blocked (double Lock, recursive RLock, Wait forever)
fatal error: sync: unlock of unlocked mutexRuntime fatalNoUnlock on an unlocked Mutex
fatal error: sync: Unlock of unlocked RWMutexRuntime fatalNoSame for the write side
fatal error: sync: RUnlock of unlocked RWMutexRuntime fatalNoMore RUnlock than RLock
panic: sync: negative WaitGroup counterPanicYesExtra Done
panic: sync: WaitGroup misuse: Add called concurrently with WaitPanicYesAdd from zero racing Wait
panic: sync: WaitGroup is reused before previous Wait has returnedPanicYesNew round too early
fatal error: concurrent map writesRuntime fatalNoPlain map written concurrently
fatal error: concurrent map read and map writeRuntime fatalNoPlain map read during a write
panic: sync/atomic: store of inconsistently typed value into ValuePanicYesatomic.Value given a second type
panic: sync/atomic: store of nil value into ValuePanicYesValue.Store(nil)
WARNING: DATA RACE + exit status 66Race detectorn/aUnsynchronised conflicting access
passes lock by value, copies lock valuego vet copylocksn/aCopied a sync value
WaitGroup.Add called from inside new goroutinego vet waitgroup (1.25)n/aAdd 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 starving

Inside 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 / commandEffect
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.outWrite profiles from tests
/debug/pprof/mutex, /debug/pprof/blockSame over HTTP via net/http/pprof
GOMAXPROCSNumber of Ps: shard count for per-P structures, parallelism of contention
b.RunParallelBenchmark with GOMAXPROCS goroutines to measure contention
kill -QUIT pid / GOTRACEBACK=allDump all goroutines of a hung process to find who holds what

Solving the classic problems ​

Problem: a counter loses increments under load ​

SolutionHowAdvantageCost
atomic.Int64hits.Add(1)Simplest, no lockOne hot cache line
Mutexlock around n++Can update related fields togetherSlower, contention
Sharded counterper-P padded shards, sum on readScales with coresMemory, read cost, no snapshot
Batch then flushlocal count per worker, add every NFewest shared writesDelayed visibility

When the counter must survive restarts, batch in memory and flush with one SQL statement per interval instead of one per request:

sql
-- 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 ​

SolutionHowAdvantageCost
singleflight.Groupg.Do(key, load)One load per key per processPer-process only; a slow load blocks all joiners
RWMutex + re-checkGetOrLoad in the rwcache snippetNo dependencyLoad runs under the write lock
sync.Map.LoadOrStorebuild, then keep the firstLock-free readsDuplicate builds possible
Distributed lock / request coalescing at the cacheRedis SET NXAcross replicasNetwork, 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 ​

What are you coordinating?hand off data,signal eventsone wordchanges aloneseveral fieldschange togetherlifecycle: wait for N,run once, limitchannel(close = Broadcast)atomic.Int64, Bool,Pointer[T]sync.Mutex(RWMutex if measured)WaitGroup, errgroup,Once, semaphore,singleflightThen run go test -race and go vet; measure before switching to RWMutex, sync.Map or sharding
SituationRecommendationExtra techniqueReason
Pass work or results between goroutinesChannelselect with ctx.Done()Ownership moves; no shared state
One counter or flagatomic.Int64 / atomic.BoolSharding if it is the top of a profileOne word, no invariant
Several fields that must change togethersync.MutexNamed field, defer UnlockInvariants span fields
Read-mostly, reads do real worksync.RWMutexBenchmark against MutexParallel readers
Read-mostly, rarely changes, many fieldsatomic.Pointer[T] copy-on-writeMutex for writersReaders never block
Grow-only cache, disjoint keyssync.MapGeneric wrapperDesigned for exactly this
One-time setupsync.OnceValue(s) / OnceStore the errorCorrect double-checked locking
Wait for N goroutinesWaitGroup.Go (1.25) or Add before goerrgroup if they can failSimple join
Bounded parallel work that can failerrgroup + SetLimitWithContextFirst error cancels the rest
Weighted admissionsemaphore.WeightedAcquire(ctx, n)Different costs per task
Duplicate concurrent loadssingleflightForget on errorsOne call per key
Wait for a complex condition on shared statesync.CondLoop around WaitChannels cannot express it cleanly
Reuse expensive temporary bufferssync.PoolCap size, resetLower GC pressure
State shared across processes or machinesNot syncDatabase row locks, Redis lock, leader electionIn-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).

  1. 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
  1. Compare RWMutex with Mutex, 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/op
  1. Make a race and watch the detector: write n++ in two goroutines (the program in The race detector) and run go run -race .; expect WARNING: DATA RACE and exit status 66. Replace n++ with an atomic.Int64 and the report disappears.

  2. Lock a mutex twice in main and run it: fatal error: all goroutines are asleep - deadlock! with goroutine 1 [sync.Mutex.Lock]. Then call Unlock on a fresh mutex: fatal error: sync: unlock of unlocked mutex.

  3. Write a plain map from eight goroutines without a lock: fatal error: concurrent map writes. Then change it to the syncmap.Map wrapper or a map plus Mutex.

  4. Add a value receiver to a struct with a mutex and run go vet: passes lock by value. Move wg.Add(1) inside the goroutine and run go vet: WaitGroup.Add called from inside new goroutine.

  5. Collect a mutex profile from the profile test and read it with go tool pprof -top (output in Mutex profiles).

Common misconceptions ​

BeliefReality
A goroutine can re-lock a mutex it holdsGo mutexes are not reentrant; the second Lock blocks forever
Only the locking goroutine may unlockAny goroutine may; there is no owner
RWMutex is always faster for readsEach RLock writes a shared counter; for tiny sections Mutex often wins
A read lock can be upgradedNo upgrade or downgrade; release and re-check
Cond.Wait can wake spuriously in GoIt cannot; the loop is needed because another goroutine may change the state first
wg.Add(1) inside the goroutine is fineWait can return before it runs; vet (1.25) reports it
Once retries if the function failedNever; a panic also counts as done
sync.Pool is a connection poolThe GC may drop items at any time; only for disposable objects
sync.Map is the default concurrent mapSpecialised; map plus Mutex is the default
Atomics are relaxed, like C++ memory_order_relaxedAll Go atomics are sequentially consistent
Two atomic updates form one consistent changeEach is atomic alone; use a Mutex for multi-field invariants
The runtime detects every deadlockOnly when all goroutines are blocked; a server just hangs
No race report means race-freeOnly executed interleavings are checked
A Go mutex protects data across instancesIt is in-process memory; use database or distributed locks

Cheat sheet ​

TopicRemember
Mutex shapemu sync.Mutex named field next to guarded fields; Lock(); defer Unlock()
Never copyPointer receivers; go vet copylocks
ReentrancyNone; split into fooLocked helpers
TryLockRare; failed call has no memory effect
FairnessNormal mode unfair and fast; starvation mode after 1 ms waits, FIFO hand-off
RWMutexWriter preference; no recursive RLock; no upgrade; benchmark first
WaitGroupAdd before go or wg.Go (1.25); defer Done; pass by pointer
OnceOnceValue(s) for lazy singletons; errors and panics are cached
CondHold L; for !cond { Wait() }; usually use channels
PoolStore pointers, Reset on Get, cap sizes, GC may clear it
sync.MapGrow-only or disjoint keys; wrap for types; Range not a snapshot
AtomicsTyped values (atomic.Int64, Bool, Pointer[T]); sequentially consistent
CAS loopLoad, compute, CompareAndSwap, retry
DeadlocksGlobal lock order; no blocking calls under a lock
False sharingPad hot per-core data to a cache line (64 or 128 bytes)
x/syncerrgroup.SetLimit, semaphore.Weighted, singleflight.Do
Diagnose-race, go vet, SetMutexProfileFraction, /debug/pprof/mutex

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Critical sectionCode that only one goroutine may run at a time, between Lock and Unlock
sync.MutexMutual exclusion lock; zero value unlocked; not reentrant
Lock / UnlockAcquire and release a mutex
TryLockAcquire only if free; returns false otherwise (Go 1.18)
Reentrant mutexA lock the same owner can take again; Go has none
Lock scopeThe span of code that holds the lock; keep it short
copylocksgo vet analyzer that reports copied sync values
noCopyZero-size marker type vet uses to detect copies
Embedding mutexPutting sync.Mutex as an anonymous field; leaks Lock into the API
ContentionGoroutines waiting for the same lock
Normal modeMutex mode where new arrivals can barge ahead of woken waiters
Starvation modeMutex mode with direct FIFO hand-off after a waiter waits more than 1 ms
SpinningBusy-waiting briefly before parking, on multicore machines
sync.RWMutexReader/writer lock: many readers or one writer
RLock / RUnlockAcquire and release the shared (read) side
Writer preferenceA waiting writer blocks new readers so it cannot starve
Lock upgradeTurning a read lock into a write lock; not supported
sync.WaitGroupCounter of outstanding tasks; Wait blocks until zero
Add / Done / WaitRaise, lower by one, and wait for zero on a WaitGroup
WaitGroup.GoGo 1.25 method: Add(1), start f, Done when it returns
sync.OnceRuns a function exactly once; others wait for it
OnceFunc / OnceValue / OnceValuesGo 1.21 helpers returning once-only functions
Lazy initializationBuilding a value on first use instead of at start-up
sync.CondCondition variable tied to a Locker
Wait (Cond)Unlock, sleep until signalled, relock
Signal / BroadcastWake one / all goroutines waiting on a Cond
Spurious wakeupWaking without a signal; possible in POSIX, not in Go's Cond
sync.PoolPer-P cache of reusable objects that the GC may clear
Get / PutTake an object from / return it to a pool
GC-clearedPool contents are dropped across garbage collections
Victim cacheSecond-chance pool cache that survives one GC (Go 1.13)
Buffer reuseRecycling *bytes.Buffer values to cut allocations
sync.MapConcurrent map optimised for grow-only and disjoint-key use
Load / Store / LoadOrStore / Rangesync.Map read, write, insert-if-absent and iteration
sync/atomicPackage of indivisible memory operations
atomic.Int64Typed 64-bit atomic integer, auto-aligned (Go 1.19)
atomic.BoolTyped atomic boolean
atomic.Pointer[T]Typed atomic pointer for copy-on-write publication
atomic.ValueAtomic holder of any value of one concrete type
Add / Load / Store / SwapAtomic increment, read, write and exchange
CompareAndSwap (CAS)Replace only if the current value equals the expected one
Lock-freeProgress through atomic retries rather than blocking on locks
ABA problemCAS succeeds although the value changed and changed back
Sequentially consistentAll atomics appear in one global order consistent with each goroutine
Happens-beforeOrdering that guarantees a write is visible to a read
Synchronizes beforeThe memory model's name for a cross-goroutine edge
Data raceConcurrent accesses to one variable, at least one a write, with no happens-before
DeadlockGoroutines waiting on each other forever
Lock orderingAlways acquiring multiple locks in one global order
Lock hierarchyLayered order: hold a higher-level lock, take only lower-level ones
False sharingIndependent variables on one cache line slowing each other
Cache lineUnit of memory moved between caches (64 or 128 bytes)
PaddingUnused bytes that push data onto separate cache lines
Sharded counterN independent counters summed on read
errgroupx/sync group with first error and context cancellation
SetLimitCaps active goroutines in an errgroup
semaphore.Weightedx/sync semaphore where each acquire takes n units
singleflightx/sync duplicate call suppression per key
Race detector-race instrumentation that reports data races at run time
Mutex profilepprof profile of lock contention delay
SetMutexProfileFractionSets the sampling rate of the mutex profile
Block profilepprof profile of all blocking (channels, select, locks)
flockOS advisory file lock; PHP's cross-process lock primitive
APCuPHP 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.

NeedPHP / LaravelGo
Mutual exclusion on one machineflock($fp, LOCK_EX) on a filesync.Mutex (in-process)
Mutual exclusion across serversCache::lock('key', 10)->get(...) (Redis/database)Same idea: database row lock or Redis lease; not sync
Shared in-memory cacheAPCu (apcu_fetch, apcu_store), per FPM poolsync.Map, map + Mutex, atomic.Pointer
Run once per processStatic property / service container singletonsync.OnceValue
Wait for parallel workHttp::pool, queued jobs, Bus::batchWaitGroup, errgroup
CounterRedis::incr('hits') or apcu_incatomic.Int64 (plus a periodic flush)
php
<?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 ​

Built by Morteza Negahi