Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readGo
#Go#Concurrency#Synchronization
3D illustration of concurrent thread gates regulated by glowing mutex locks and a WaitGroup barrier counter

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.Mutex guards a critical section; Lock/Unlock must be paired on every path, and defer mu.Unlock() immediately after Lock is the habit that makes that true.
  • A Mutex is not reentrant: locking twice in the same goroutine deadlocks, and no error says so.
  • sync.RWMutex allows concurrent RLock but a pending Lock blocks new readers, so it helps read-heavy workloads and hurts mixed ones.
  • sync.WaitGroup counts goroutines; Add must happen before the goroutine starts, and Wait may run concurrently with Add only for counts added before the wait begins.
  • sync.Once runs 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 vet reports copied locks.
  • sync.Cond exists for waiting on a predicate that another goroutine changes; sync.Map is for specific access patterns, not a general replacement for a mutex-guarded map.

Basic syntax and type signatures

go
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 ran
go
type 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

PrimitiveProtectsBlocksReentrantCopy after use
Mutexone critical sectionall other lockersnoinvalid
RWMutexa section, read or writewriters block readersnoinvalid
WaitGroupnothing (synchronization only)Wait until count is zeron/ainvalid
Onceone initializationevery caller after the firstn/ainvalid
Condnothing; pairs with a Mutexwaiters until Signal/Broadcastn/ainvalid
Mapits own contentsper-key operationsn/ainvalid
channelownership transfersender/receivern/an/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

go
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

go
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

go
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

go
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

go
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

SymptomCauseFix
Deadlock with no goroutine dump progressLock twice in one goroutinerestructure, or use a TryLock path to detect
fatal error: all goroutines are asleep - deadlock!Wait with a count that never reaches zeroensure every Add has a matching Done
panic: sync: negative WaitGroup counterDone called more times than Addpair Add(1) with exactly one Done
panic: sync: WaitGroup is reused before previous Wait has returnedAdd after Wait startedadd all counts before Wait
go vet: copylocksa struct with a mutex passed or assigned by valueuse pointer receivers and pointers in containers
fatal error: sync: RUnlock of unlocked RWMutexRUnlock without a matching RLockpair them with defer in the same scope
Race detector: write/read conflict on a mapmap read outside the locktake the read lock around the access, including len
Initialization runs twicea bool flag checked without a lockuse 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 tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.