Go sync Package: Mutex, RWMutex, WaitGroup, and sync.Once Explained
The primitives that make shared memory safe in Go, the reentrancy and copying traps that break them silently, and when sync.Once or sync.Cond beats a plain mutex.

The sync package holds the primitives that make shared memory safe between goroutines without channels: Mutex for exclusive access, RWMutex for many readers, WaitGroup for waiting on a set of goroutines, Once for exactly-one initialization, and Cond for waiting on a condition. They are low-level and unforgiving: none of them detects misuse at compile time, and most of the bugs they cause are races that appear only under load.
Quick Summary
sync.Mutexguards a critical section;Lock/Unlockmust be paired on every path, anddefer mu.Unlock()immediately afterLockis the habit that makes that true.- A
Mutexis not reentrant: locking twice in the same goroutine deadlocks, and no error says so. sync.RWMutexallows concurrentRLockbut a pendingLockblocks new readers, so it helps read-heavy workloads and hurts mixed ones.sync.WaitGroupcounts goroutines;Addmust happen before the goroutine starts, andWaitmay run concurrently withAddonly for counts added before the wait begins.sync.Onceruns a function exactly once and blocks every other caller until the first finishes, which makes it the right tool for lazy initialization with error handling kept separate.- Copying any of these after first use is a bug; all three carry internal state, and
go vetreports copied locks. sync.Condexists for waiting on a predicate that another goroutine changes;sync.Mapis for specific access patterns, not a general replacement for a mutex-guarded map.
Basic syntax and type signatures
type Mutex struct{ /* unexported */ }
func (m *Mutex) Lock()
func (m *Mutex) Unlock()
func (m *Mutex) TryLock() bool // Go 1.18+
type RWMutex struct{ /* unexported */ }
func (rw *RWMutex) Lock()
func (rw *RWMutex) Unlock()
func (rw *RWMutex) RLock()
func (rw *RWMutex) RUnlock()
type WaitGroup struct{ /* unexported */ }
func (wg *WaitGroup) Add(delta int)
func (wg *WaitGroup) Done()
func (wg *WaitGroup) Wait()
type Once struct{ /* unexported */ }
func (o *Once) Do(f func())
func (o *Once) Do(f func()) bool // Go 1.21+ returns whether f rantype Counter struct {
mu sync.Mutex
n int
}
func (c *Counter) Inc() {
c.mu.Lock()
defer c.mu.Unlock()
c.n++
}
func (c *Counter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.n
}
// WaitGroup: Add before the goroutine, Done inside it, Wait after launching.
func runAll(tasks []func()) {
var wg sync.WaitGroup
for _, task := range tasks {
wg.Add(1)
go func(task func()) {
defer wg.Done()
task()
}(task)
}
wg.Wait()
}The two details that break naive versions of this code: task must be passed as a parameter (before Go 1.22 the loop variable was shared, and even with the 1.22 change, capturing is a habit worth keeping explicit), and wg.Add(1) must be outside the goroutine, because Done can otherwise run before Add and make the counter negative.
Comparison of the primitives
| Primitive | Protects | Blocks | Reentrant | Copy after use |
|---|---|---|---|---|
Mutex | one critical section | all other lockers | no | invalid |
RWMutex | a section, read or write | writers block readers | no | invalid |
WaitGroup | nothing (synchronization only) | Wait until count is zero | n/a | invalid |
Once | one initialization | every caller after the first | n/a | invalid |
Cond | nothing; pairs with a Mutex | waiters until Signal/Broadcast | n/a | invalid |
Map | its own contents | per-key operations | n/a | invalid |
| channel | ownership transfer | sender/receiver | n/a | n/a |
Cond is the least used and the least recommended: in almost every case a channel closes the same gap with less state to get wrong. sync.Map is specialized for keys written once and read many times, or disjoint key sets per goroutine; for everything else a map behind a Mutex is faster and type-safe.
Practical edge cases and deep dives
1. The double-checked lock and why Once is the fix
type Client struct {
mu sync.Mutex
conn *sql.DB
}
// Wrong: two goroutines can both find conn nil before either assigns it.
func (c *Client) Get() *sql.DB {
if c.conn == nil {
c.mu.Lock()
defer c.mu.Unlock()
c.conn = open() // still racy on the read above without atomic access
}
return c.conn
}
// Right: Once serializes the whole initialization and publishes it safely.
type Service struct {
once sync.Once
db *sql.DB
err error
}
func (s *Service) DB() (*sql.DB, error) {
s.once.Do(func() {
s.db, s.err = openWithRetry()
})
return s.db, s.err
}sync.Once guarantees a happens-before edge: everything written inside Do is visible to every goroutine that returns from Do, which the double-checked version does not provide without atomic.Pointer or similar. Assigning the error inside the closure and returning it afterwards is the standard way to keep the failure memoized instead of retried on every call.
2. RWMutex under a write-heavy load
type Cache struct {
mu sync.RWMutex
m map[string][]byte
}
func (c *Cache) Get(key string) ([]byte, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok := c.m[key]
return v, ok
}
func (c *Cache) Set(key string, v []byte) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[key] = v
}RLock is only a win when reads dominate and hold the lock briefly. Under a stream of writes, each Lock waits for every outstanding reader and blocks new RLock calls while it waits, so throughput falls below a plain Mutex. The same applies when readers do real work under RLock: the write path stalls, latency spikes, and the profile shows time in sync.(*RWMutex).Lock. A plain Mutex with short critical sections is usually the better default; measure before choosing RWMutex.
3. WaitGroup reuse and the Add-inside-Wait race
func batch(ctx context.Context, items []Item) error {
var wg sync.WaitGroup
errCh := make(chan error, len(items))
for _, item := range items {
wg.Add(1) // before `go`, never inside
go func(item Item) {
defer wg.Done()
if err := process(ctx, item); err != nil {
errCh <- err
}
}(item)
}
wg.Wait()
close(errCh)
for err := range errCh {
return err
}
return nil
}Reusing one WaitGroup for sequential phases is legal only after the previous Wait returned. Put wg.Add(1) inside the goroutine and the wait may observe a zero counter and return while work is still being scheduled — a race the detector reports as WaitGroup is reused before previous Wait has returned or, worse, silently misses. The buffered error channel sized to len(items) avoids a goroutine blocked on send while Wait waits for it to finish.
4. Mutex copied by value in a struct that is passed around
type Registry struct {
mu sync.Mutex
entries map[string]string
}
// Wrong: value receiver copies the mutex, so the lock protects a copy.
func (r Registry) Add(k, v string) {
r.mu.Lock()
defer r.mu.Unlock()
r.entries[k] = v
}
// Right: pointer receiver, and the map is initialized once.
func (r *Registry) AddOK(k, v string) {
r.mu.Lock()
defer r.mu.Unlock()
if r.entries == nil {
r.entries = make(map[string]string)
}
r.entries[k] = v
}The value receiver version compiles, does not race (each copy has its own lock), and silently loses writes. go vet's copylocks check catches most of these, which is a reason to keep it enabled in CI. The same trap appears when a struct containing a mutex is stored in a slice or returned by value.
5. sync.Cond for a bounded queue, and why a channel is usually better
type Queue struct {
mu sync.Mutex
cond *sync.Cond
items []int
closed bool
}
func NewQueue() *Queue {
q := &Queue{}
q.cond = sync.NewCond(&q.mu)
return q
}
func (q *Queue) Push(v int) {
q.mu.Lock()
defer q.mu.Unlock()
q.items = append(q.items, v)
q.cond.Signal()
}
func (q *Queue) Pop() (int, bool) {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.items) == 0 && !q.closed {
q.cond.Wait() // atomically unlocks and re-locks on wake
}
if len(q.items) == 0 {
return 0, false
}
v := q.items[0]
q.items = q.items[1:]
return v, true
}
func (q *Queue) Close() {
q.mu.Lock()
defer q.mu.Unlock()
q.closed = true
q.cond.Broadcast()
}The for around Wait is mandatory: a spurious wake or another consumer taking the item means the predicate must be re-tested. Signal wakes one waiter, Broadcast wakes all, and neither releases the lock — Wait does that itself, then reacquires before returning. An equivalent with a buffered channel and a close is shorter and cancels naturally with a context, which is why Cond stays rare.
Common mistakes and compiler errors
| Symptom | Cause | Fix |
|---|---|---|
| Deadlock with no goroutine dump progress | Lock twice in one goroutine | restructure, or use a TryLock path to detect |
fatal error: all goroutines are asleep - deadlock! | Wait with a count that never reaches zero | ensure every Add has a matching Done |
panic: sync: negative WaitGroup counter | Done called more times than Add | pair Add(1) with exactly one Done |
panic: sync: WaitGroup is reused before previous Wait has returned | Add after Wait started | add all counts before Wait |
go vet: copylocks | a struct with a mutex passed or assigned by value | use pointer receivers and pointers in containers |
fatal error: sync: RUnlock of unlocked RWMutex | RUnlock without a matching RLock | pair them with defer in the same scope |
| Race detector: write/read conflict on a map | map read outside the lock | take the read lock around the access, including len |
| Initialization runs twice | a bool flag checked without a lock | use sync.Once or atomic.Bool |
The reliable way to find these before production is to run the test suite with go test -race and to keep critical sections small enough to review by eye: a mutex whose guarded region spans more than a few statements is where both deadlocks and copied-lock mistakes hide. When two locks must be held, fix an ordering and document it, because the second lock acquired by one goroutine and the reverse order in another is the deadlock that shows up only in the field.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.