Every Go programmer has typed mu.Lock() ten thousand times without asking what it costs. The answer is surprising: in the uncontended case, it is a single compare-and-swap and an immediate return. Everything else — spinning, sleeping, fairness, the queue of blocked goroutines — is slow-path machinery packed into two machine words. Reading the actual implementation is one of the best lessons in systems design in the standard library: throughput against fairness, CPU burn against scheduler load, and how to build an escape hatch for when those trade-offs go wrong.
This post walks through how sync.Mutex actually works under contention: the bit layout that holds its entire state, when it decides to spin instead of sleep, the one-millisecond rule that flips it into starvation mode, and the runtime semaphore that queues the goroutines that lost the race.
Two words and three bits
The entire mutex is this:
type Mutex struct {
state int32
sema uint32
}
state is a packed bitfield. The low three bits are flags — locked, woken, and starving — and everything above bit 2 is a count of goroutines currently waiting on the semaphore. sema is a handle to a runtime semaphore used for parking waiters. There is no pointer to a queue structure, no heap allocation, no embedded goroutine list. A zero state means unlocked, unstarved, no waiters — which is why var mu sync.Mutex is ready to use with no constructor.
Packing waiter counts into the same word as the lock flags is what makes the lock cheap: a single atomic 32-bit compare-and-swap can transition the whole state at once.
The fast path is one CAS away
Lock() tries the cheap thing first:
func (m *Mutex) Lock() {
// Fast path: grab unlocked mutex.
if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) {
return
}
// Slow path (outlined so that the fast path can be inlined)
m.lockSlow()
}
If the mutex was free, one CAS flips it to locked and you are done — a few nanoseconds, fully inlined, no function call into the runtime. The slow path is deliberately pulled out into lockSlow() so the inliner can keep the fast path tiny. Unlock() mirrors this: it subtracts the lock bit with a single atomic add, and only calls into the slow path if that add left a nonzero state, which happens exactly when someone is waiting.
This is the shape most fast locks take: an optimistic single-word path, and a heavy fall-back that the hot case never touches.
Spinning: burning CPU to dodge the scheduler
When a goroutine finds the mutex taken, its first instinct in the slow path is not to sleep — it is to spin briefly. The reasoning: the holder may release within a few hundred nanoseconds, and parking plus waking a goroutine through the scheduler costs far more than a few wasted iterations. Spinning is only allowed when all of these hold:
- The mutex is locked but not in starvation mode — in starvation mode ownership will be handed to a queued waiter, so spinning is pointless.
runtime_canSpinsays yes — there are other threads running (spinning on a single-CPU machine only delays the real owner) and the goroutine has not exceeded the iteration cap (four).- There is at least one queued waiter, and the goroutine successfully sets the woken flag — this tells
Unlockthat someone is already actively racing for the lock, so it should not bother waking anyone else from the queue.
The spin itself is runtime_doSpin(), which executes a few PAUSE-style instructions that keep the CPU pipeline from speculating wildly while the goroutine re-reads state. If the holder releases during the spin, the spinner acquires the lock without ever touching the scheduler. If not, it stops burning CPU and moves on to the queue.
The unfairness problem, and the 1 millisecond rule
Here is the design tension at the heart of the lock. Suppose goroutine W has been sleeping in the queue, and the holder releases. W is woken — but W is not running yet. Meanwhile a fresh goroutine F arrives, is already on a CPU, and grabs the lock with a fast CAS before W even gets scheduled. This is called barging, and it is deliberate: letting hot, already-running goroutines win keeps throughput high, because a woken waiter pays wake-up latency on every handoff.
But barging has a failure mode. Under heavy, sustained contention, W can lose the race over and over — woken, beaten, re-queued at the front of the queue (so at least it is first in line next time). A pathological workload can keep a waiter starving indefinitely while barging goroutines cycle the lock between themselves.
The mutex’s answer is starvation mode. Every waiter tracks how long it has been waiting. If it fails to acquire the lock for more than one millisecond, it flips the starving bit on the mutex state. From that point:
- New arrivals do not spin and do not attempt the CAS. Even though the mutex looks unlocked, they queue at the tail like everyone else.
Unlockperforms a direct handoff: ownership passes to the waiter at the front of the queue, and the unlocking goroutine yields its time slice so the woken waiter starts running immediately.
Starvation mode is expensive — every handoff now pays wake-up latency — so it is meant to be a temporary state, and it exits aggressively. When a waiter finally receives ownership, it switches back to normal mode if it waited less than a millisecond, or if it is the last waiter in the queue. The exit logic matters more than it looks: without it, two goroutines can ping-pong a starving mutex between themselves forever, in lock-step, while everyone else waits.
Queuing without allocating: the semaphore table
When a goroutine gives up spinning, it increments the waiter count in state and calls runtime_SemacquireMutex on the sema word. That call descends into the runtime’s semaphore table: a fixed array of 251 buckets, each holding a balanced tree (a treap) of waiters, with semaphore addresses hashed to buckets so unrelated locks rarely share a tree. One telling detail: if the goroutine has already waited on this mutex before, it passes a lifo flag, so it is re-inserted at the front of the queue — that is the implementation of the “re-queued at front” behavior from the previous section.
The tree gives the runtime two useful properties: it can wake waiters in queue order when handing off, and it can hold arbitrarily many waiters per semaphore without any per-mutex heap allocation. All of this lives behind a single uint32.
Seeing the modes for yourself
A small probe makes the contention machinery observable. Eight goroutines hammer one mutex for two seconds, holding it briefly each time:
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
var (
mu sync.Mutex
wg sync.WaitGroup
acquires [8]atomic.Int64
)
deadline := time.Now().Add(2 * time.Second)
for i := range acquires {
wg.Add(1)
go func(id int) {
defer wg.Done()
var n int64
for time.Now().Before(deadline) {
mu.Lock()
n++
for j := 0; j < 100; j++ { // hold it briefly
}
mu.Unlock()
}
acquires[id].Store(n)
}(i)
}
wg.Wait()
for id := range acquires {
fmt.Printf("goroutine %d: %d acquires\n", id, acquires[id].Load())
}
}
Run it and you will see unequal-but-bounded spreads across goroutines — the mutex barges aggressively to keep throughput up, while the one-millisecond rule quietly caps how far any single waiter can fall behind. Shrink the critical section to almost nothing and the spread changes; make it long, or add more goroutines than CPUs, and you push the lock toward starvation-mode handoffs.
What this means for your code
Three practical takeaways fall out of the implementation:
- Keep critical sections short. Every microsecond spent holding the lock is multiplied across every waiter, and long holds convert a cheap fast path into a stream of scheduler park-and-wake cycles. Shrink what happens under the lock; do the expensive work (I/O, parsing, computation) outside it.
- Treat heavy contention on one mutex as a design signal. When the same lock serializes many goroutines, the fix is rarely tuning — it is sharding the lock (per-key, per-shard, per-connection), or restructuring so fewer operations need it at all.
TryLockis mode-aware. It fails immediately if the mutex is locked or starving, so it will never barge past queued waiters. It exists for cases like “skip the work if someone else is doing it,” not for building your own retry loops around contention.
The design generalizes beyond Go. Optimistic fast path, bounded spinning, delayed fairness that only engages when evidence shows it is needed, and a handoff mode with a clear exit condition — this pattern shows up in futex-based locks in the Linux kernel and in most production mutex implementations. When you next reach for a lock in any language, it is worth remembering that “just block until it is free” was never on the table, and that the interesting engineering is entirely in the edge cases.