Chapter 1 · Section 4 of 8 · 11 min read
In Go: reading sync.Mutex
Using sync.Mutex
Here are the two types from the problem section, written with a mutex. Everything in this section is from Go 1.25.2.
// Counter is a counter that many goroutines may increment at once.
//
// The mutex guards n. Every read and write of n happens while it is held, so
// the three steps of an increment can never interleave with another
// goroutine's steps.
type Counter struct {
mu sync.Mutex // guards n
n int
}
// Inc adds one to the counter.
func (c *Counter) Inc() {
c.mu.Lock()
defer c.mu.Unlock()
v := c.n
runtime.Gosched() // same gap as the unprotected version, now harmless
c.n = v + 1
}
// Value returns the current count.
func (c *Counter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.n
}
// Account shows why the critical section must cover the check as well as the
// change: "is there enough money?" and "take the money" are one decision.
type Account struct {
mu sync.Mutex // guards balance
balance int
}
// NewAccount returns an account holding balance.
func NewAccount(balance int) *Account { return &Account{balance: balance} }
// Withdraw takes amount out of the account, or returns ErrInsufficientFunds.
func (a *Account) Withdraw(amount int) error {
a.mu.Lock()
defer a.mu.Unlock()
if a.balance < amount {
return ErrInsufficientFunds
}
runtime.Gosched() // a window where an unprotected version would go wrong
a.balance -= amount
return nil
}
// Balance returns the current balance.
func (a *Account) Balance() int {
a.mu.Lock()
defer a.mu.Unlock()
return a.balance
}
Five things to notice:
- The zero value works. The documentation says: "The zero value for a Mutex is an unlocked mutex." You never construct one. A
Counter{}is ready to use. defer c.mu.Unlock()runs when the function returns by any path, including an earlyreturnand a panic. It is the standard way to make sure the lock is released.Withdrawholds the lock across the check and the change. That is what prevents the overdraft.Valuelocks too. Reading while another goroutine writes is a data race, so reads need the lock as well.- Do not copy a mutex. The documentation says: "A Mutex must not be copied after first use." The Pitfalls section shows the warning
go vetgives.
The tests run under the race detector:
go vet ./chapters/01-mutex/code
go test -race ./chapters/01-mutex/codeTestNoLockCounterLosesUpdates shows the other side. It builds only without -race, and checks that the version with the mutex removed ends below the target. On my machine one run reported 8000 increments, final count 1139, 6861 lost. TestNoLockCounterIsRacy has the build tag raceDemo and fails on purpose with -race -tags raceDemo, so you can see the detector flag the same code.
Where the real code lives
The type you use, sync.Mutex, is a thin wrapper. In Go 1.25.2, sync.Mutex in src/sync/mutex.go holds an internal/sync.Mutex and forwards each call to it: its Unlock is literally m.mu.Unlock(). The algorithm is in src/internal/sync/mutex.go. The rest of this section reads that file.
The state: two words
// A Mutex is a mutual exclusion lock.
//
// See package [sync.Mutex] documentation.
type Mutex struct {
state int32
sema uint32
}
const (
mutexLocked = 1 << iota // mutex is locked
mutexWoken
mutexStarving
mutexWaiterShift = iotaA Mutex is two 32-bit values: state and sema. The whole mutex fits in state:
- bit 0,
mutexLocked: someone holds the lock; - bit 1,
mutexWoken: a goroutine has been woken or is spinning, soUnlockdoes not need to wake another; - bit 2,
mutexStarving: the mutex is in starvation mode (explained below); - the remaining bits, from
mutexWaiterShift(3) upward: how many goroutines are waiting. You can see the code useold>>mutexWaiterShiftas the waiter count.
sema is a semaphore the goroutines sleep on. Chapter 4 covers semaphores.
Lock: the fast path
// Lock locks m.
//
// See package [sync.Mutex] documentation.
func (m *Mutex) Lock() {
// Fast path: grab unlocked mutex.
if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) {
if race.Enabled {
race.Acquire(unsafe.Pointer(m))
}
return
}
// Slow path (outlined so that the fast path can be inlined)
m.lockSlow()
}If the mutex is free (state is 0), one atomic compare-and-swap sets it to locked and Lock returns. That single instruction is the whole cost of an uncontended lock. Otherwise the code calls lockSlow. The comment says the slow path is "outlined so that the fast path can be inlined", which keeps the common case small. Chapter 13 explains compare-and-swap.
Lock: spinning
func (m *Mutex) lockSlow() {
var waitStartTime int64
starving := false
awoke := false
iter := 0
old := m.state
for {
// Don't spin in starvation mode, ownership is handed off to waiters
// so we won't be able to acquire the mutex anyway.
if old&(mutexLocked|mutexStarving) == mutexLocked && runtime_canSpin(iter) {
// Active spinning makes sense.
// Try to set mutexWoken flag to inform Unlock
// to not wake other blocked goroutines.
if !awoke && old&mutexWoken == 0 && old>>mutexWaiterShift != 0 &&
atomic.CompareAndSwapInt32(&m.state, old, old|mutexWoken) {
awoke = true
}
runtime_doSpin()
iter++
old = m.state
continue
}If the lock is held and the mutex is not in starvation mode, a goroutine may spin: loop for a short while hoping the holder releases soon. Whether spinning is allowed is decided by the runtime:
// Active spinning for sync.Mutex.
//
//go:linkname internal_sync_runtime_canSpin internal/sync.runtime_canSpin
//go:nosplit
func internal_sync_runtime_canSpin(i int) bool {
// sync.Mutex is cooperative, so we are conservative with spinning.
// Spin only few times and only if running on a multicore machine and
// GOMAXPROCS>1 and there is at least one other running P and local runq is empty.
// As opposed to runtime mutex we don't do passive spinning here,
// because there can be work on global runq or on other Ps.
if i >= active_spin || numCPUStartup <= 1 || gomaxprocs <= sched.npidle.Load()+sched.nmspinning.Load()+1 {
return false
}
if p := getg().m.p.ptr(); !runqempty(p) {
return false
}
return true
}
//go:linkname internal_sync_runtime_doSpin internal/sync.runtime_doSpin
//go:nosplit
func internal_sync_runtime_doSpin() {
procyield(active_spin_cnt)
}The comment says: "sync.Mutex is cooperative, so we are conservative with spinning." The conditions in the code are: the goroutine has spun fewer than active_spin times; the machine has more than one CPU; GOMAXPROCS is greater than the number of idle and spinning processors plus one (so at least one other processor is busy running Go code); and the local run queue is empty. active_spin is 4 and active_spin_cnt is 30 in src/runtime/lock_spinbit.go (lines 54-55), where a comment marks them as "referenced in proc.go for sync.Mutex implementation".
While spinning, a goroutine tries to set mutexWoken. The comment explains why: "to inform Unlock to not wake other blocked goroutines." A spinner is already awake and competing, so waking a sleeper as well would be wasted work.
Lock: joining the queue and sleeping
if atomic.CompareAndSwapInt32(&m.state, old, new) {
if old&(mutexLocked|mutexStarving) == 0 {
break // locked the mutex with CAS
}
// If we were already waiting before, queue at the front of the queue.
queueLifo := waitStartTime != 0
if waitStartTime == 0 {
waitStartTime = runtime_nanotime()
}
runtime_SemacquireMutex(&m.sema, queueLifo, 2)
starving = starving || runtime_nanotime()-waitStartTime > starvationThresholdNs
old = m.stateWhen spinning does not work, the goroutine updates state with a compare-and-swap, which also adds itself to the waiter count, and then sleeps with runtime_SemacquireMutex. Two details matter:
queueLifo := waitStartTime != 0. A goroutine that has already waited once and been woken goes to the front of the queue the next time, not the back, as the comment says: "If we were already waiting before, queue at the front of the queue."- After waking, it records whether it has now waited longer than
starvationThresholdNs. That constant is1e6nanoseconds, which is 1 millisecond.
Two modes
The big comment in the source describes the policy. Read it in full:
// Mutex fairness.
//
// Mutex can be in 2 modes of operations: normal and starvation.
// 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. New arriving goroutines have an advantage -- they are
// already running on CPU and there can be lots of them, so a woken up
// waiter has good chances of losing. In such case it is queued at front
// of the wait queue. 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.
// New arriving goroutines don't try to acquire the mutex even if it appears
// to be unlocked, and don't try to spin. Instead they queue themselves at
// the tail of the wait queue.
//
// If a waiter receives ownership of the mutex and sees that either
// (1) it is the last waiter in the queue, or (2) it waited for less than 1 ms,
// it switches mutex back to normal operation mode.
//
// Normal mode has considerably better performance as a goroutine can acquire
// a mutex several times in a row even if there are blocked waiters.
// Starvation mode is important to prevent pathological cases of tail latency.
starvationThresholdNs = 1e6In short:
- Normal mode. Waiters queue first-in, first-out. But when
Unlockwakes the first waiter, that waiter "does not own the mutex and competes with new arriving goroutines over the ownership." A goroutine that is already running has an advantage, so the woken one "has good chances of losing". Normal mode is fast: the comment says "a goroutine can acquire a mutex several times in a row even if there are blocked waiters." - Starvation mode. If a waiter fails to get the mutex for more than 1 ms, it switches the mutex to starvation mode. Now
Unlockhands ownership directly to the waiter at the front of the queue. New arrivals do not try to take the lock and do not spin. They join the back of the queue. The comment gives the purpose: "Starvation mode is important to prevent pathological cases of tail latency." - Back to normal. A waiter that receives ownership leaves starvation mode if it was the last in the queue or waited less than 1 ms.
Receiving a handoff
if old&mutexStarving != 0 {
// If this goroutine was woken and mutex is in starvation mode,
// ownership was handed off to us but mutex is in somewhat
// inconsistent state: mutexLocked is not set and we are still
// accounted as waiter. Fix that.
if old&(mutexLocked|mutexWoken) != 0 || old>>mutexWaiterShift == 0 {
throw("sync: inconsistent mutex state")
}
delta := int32(mutexLocked - 1<<mutexWaiterShift)
if !starving || old>>mutexWaiterShift == 1 {
// Exit starvation mode.
// Critical to do it here and consider wait time.
// Starvation mode is so inefficient, that two goroutines
// can go lock-step infinitely once they switch mutex
// to starvation mode.
delta -= mutexStarving
}
atomic.AddInt32(&m.state, delta)
break
}When a woken goroutine finds the mutex in starvation mode, the lock was handed to it. The state is "somewhat inconsistent", in the code's words: mutexLocked is not set and the goroutine is still counted as a waiter. The code fixes both with one atomic add. It also decides whether to leave starvation mode, with a comment worth reading twice: "Starvation mode is so inefficient, that two goroutines can go lock-step infinitely once they switch mutex to starvation mode."
Unlock
func (m *Mutex) Unlock() {
if race.Enabled {
_ = m.state
race.Release(unsafe.Pointer(m))
}
// Fast path: drop lock bit.
new := atomic.AddInt32(&m.state, -mutexLocked)
if new != 0 {
// Outlined slow path to allow inlining the fast path.
// To hide unlockSlow during tracing we skip one extra frame when tracing GoUnblock.
m.unlockSlow(new)
}
}func (m *Mutex) unlockSlow(new int32) {
if (new+mutexLocked)&mutexLocked == 0 {
fatal("sync: unlock of unlocked mutex")
}
if new&mutexStarving == 0 {
old := new
for {
// If there are no waiters or a goroutine has already
// been woken or grabbed the lock, no need to wake anyone.
// In starvation mode ownership is directly handed off from unlocking
// goroutine to the next waiter. We are not part of this chain,
// since we did not observe mutexStarving when we unlocked the mutex above.
// So get off the way.
if old>>mutexWaiterShift == 0 || old&(mutexLocked|mutexWoken|mutexStarving) != 0 {
return
}
// Grab the right to wake someone.
new = (old - 1<<mutexWaiterShift) | mutexWoken
if atomic.CompareAndSwapInt32(&m.state, old, new) {
runtime_Semrelease(&m.sema, false, 2)
return
}
old = m.state
}
} else {
// Starving mode: handoff mutex ownership to the next waiter, and yield
// our time slice so that the next waiter can start to run immediately.
// Note: mutexLocked is not set, the waiter will set it after wakeup.
// But mutex is still considered locked if mutexStarving is set,
// so new coming goroutines won't acquire it.
runtime_Semrelease(&m.sema, true, 2)
}
}The fast path is one atomic subtract of the locked bit. If nothing else is set (new == 0), there are no waiters and nobody is woken, and Unlock is done. Otherwise unlockSlow runs:
- It first checks the mutex really was locked. If not, it calls
fatal("sync: unlock of unlocked mutex"), which cannot be recovered, as the Pitfalls section shows. - Normal mode: if there are no waiters, or a goroutine is already woken or holds the lock, there is nothing to do. Otherwise it claims the right to wake one waiter by setting
mutexWokenand decrementing the waiter count, then callsruntime_Semrelease. - Starvation mode: it hands off.
runtime_Semrelease(&m.sema, true, 2)passestruefor the handoff argument, and the comment says the unlocking goroutine yields its time slice "so that the next waiter can start to run immediately."
There is also TryLock, which the source documents as "tries to lock m and reports whether it succeeded": one compare-and-swap, no waiting, and it never succeeds in starvation mode.
See the two modes
The simulator below is a model of this policy, not the real mutex. Each goroutine thinks for a tick or so, asks for the lock, holds it for 3 ticks, and thinks again. In normal mode an unlock wakes the first waiter, who needs 2 ticks to start running, and a goroutine that arrives in the meantime can take the free lock. A waiter that loses the race after waiting more than 8 ticks switches the mutex to starvation mode, where the lock is handed straight to the first waiter. The model's 8 ticks stand in for the runtime's 1 ms.
This animation needs JavaScript. Here is a text version of one run.
- Tick 0: Start: 4 goroutines share one mutex. Mode: normal.
- Tick 1: G2 takes the free lock.
- Tick 2: G1 asks for the lock and queues at the back. G3 asks for the lock and queues at the back. G4 asks for the lock and queues at the back.
- Tick 4: G2 unlocks. G1 is woken and will run in 2 ticks. G2 grabs the free lock before G1 can run.
- Tick 5: G1 runs but G2 already took the lock. G1 goes back to the front of the queue.
- Tick 7: G2 unlocks. G1 is woken and will run in 2 ticks. G2 grabs the free lock before G1 can run.
- Tick 8: G1 runs but G2 already took the lock. G1 goes back to the front of the queue.
- Tick 10: G2 unlocks. G1 is woken and will run in 2 ticks. G2 grabs the free lock before G1 can run.
- Tick 11: G1 runs but G2 already took the lock. G1 goes back to the front of the queue. G1 has waited 9 ticks, over the 8-tick threshold. The mutex enters starvation mode.
- Tick 13: G1 receives the lock directly from G2 after waiting 11 ticks. G2 asks for the lock and queues at the back.
- Tick 16: G3 receives the lock directly from G1 after waiting 14 ticks. G1 asks for the lock and queues at the back.
- Tick 19: G4 receives the lock directly from G3 after waiting 17 ticks. G3 asks for the lock and queues at the back.
- Tick 22: G2 receives the lock directly from G4 after waiting 9 ticks. G4 asks for the lock and queues at the back.
- Tick 25: G1 receives the lock directly from G2 after waiting 9 ticks. G2 asks for the lock and queues at the back.
- Tick 28: G3 receives the lock directly from G1 after waiting 9 ticks. G1 asks for the lock and queues at the back.
- Tick 31: G4 receives the lock directly from G3 after waiting 9 ticks. G3 asks for the lock and queues at the back.
- Tick 34: G2 receives the lock directly from G4 after waiting 9 ticks. G4 asks for the lock and queues at the back.
- Tick 37: G1 receives the lock directly from G2 after waiting 9 ticks. G2 asks for the lock and queues at the back.
- Tick 40: G3 receives the lock directly from G1 after waiting 9 ticks. G1 asks for the lock and queues at the back.
- Tick 43: G4 receives the lock directly from G3 after waiting 9 ticks. G3 asks for the lock and queues at the back.
- Tick 46: G2 receives the lock directly from G4 after waiting 9 ticks. G4 asks for the lock and queues at the back.
- Tick 49: G1 receives the lock directly from G2 after waiting 9 ticks. G2 asks for the lock and queues at the back.
- Tick 52: G3 receives the lock directly from G1 after waiting 9 ticks. G1 asks for the lock and queues at the back.
- Tick 55: G4 receives the lock directly from G3 after waiting 9 ticks. G3 asks for the lock and queues at the back.
After 120 ticks, times each goroutine got the lock: G1 9, G2 13, G3 9, G4 9. Longest wait: 17 ticks. This list shows only the first 24 ticks where something happened.
The cost of waiting
The mutex fixes the counter, and the price is that goroutines wait. How much that matters depends on how long you hold the lock and how many goroutines want it. Chapter 14 looks at spinning, and later chapters look at ways to hold locks less: read-write locks, atomic operations and designs that avoid sharing.