Contents
Dig101: dig more, simplified more and know more
sync.Mutex is Go’s mutex — simple to use, but how is it implemented, and why those choices?
A few questions, no wall of assembly — just enough to read the source later with context.
Why locks exist
Locks coordinate access. Without them, unsynchronized memory access goes wrong for two main reasons.
Non-atomic operations
If another thread can observe intermediate state halfway through an update, the operation is not atomic — not indivisible from other observers.
i++ is a read-modify-write: the CPU may touch memory more than once, so you cannot treat it as one step.

Plain loads are not always atomic either. The smallest practical unit is often one machine word (4 bytes on 32-bit, 8 on 64-bit). On a 32-bit CPU, loading an int64 may take two bus cycles; misaligned data makes it worse.
Memory reordering
Source order is not always execution order. Reordering happens in:
- The compiler — optimizations reorder within the rules of the language.
- The hardware — pipelines and caches reorder to hide latency.
Each core has caches in front of main memory:

Multiple copies need a cache coherency protocol (e.g. MESI). While one core waits for another’s line, the CPU may still execute unrelated memory ops — that is reordering from the programmer’s point of view.
For a longer write-up: Understanding memory reordering.
How Mutex builds atomic updates
Go’s atomic package exposes AddInt32, CompareAndSwapInt32, and friends. On amd64 they lower to instructions with the LOCK prefix, which asserts bus ownership for that access so the RMW is atomic on shared memory.
See runtime/internal/atomic/asm_amd64.s, e.g. Cas:
1 | // bool Cas(int32 *val, int32 old, int32 new) |
How Mutex tames reordering
LOCK-prefixed and XCHG instructions imply memory barriers: earlier ops complete before later ones cross the barrier, in the sense the architecture guarantees for synchronization.
Go-specific Mutex tuning
With atomics you could spin in a tight CAS loop. Go’s mutex does better on typical goroutine workloads.
Do not spin forever
Pure spinning burns cycles. On multi-core machines where spinning will not stall the scheduler badly, the runtime may spin up to four times, 30 cycles per attempt (runtime_canSpin, runtime_doSpin in runtime/proc.go).
Semaphore-style sleep
After spinning fails, Unix threads often use futex-style sleeping. Go’s runtime has sleep/wake on goroutines, which are cheaper to park than OS threads and faster to switch.
Starvation mode
Many waiters plus handoff races: a woken goroutine fights running ones for the lock, loses, sleeps again — latency spikes.
Go adds starvation mode: normally FIFO wake; if a waiter blocks for more than ~1ms, it moves to the front and the next unlock hands off the lock directly.
Then read sync.Mutex in the standard library with this map in mind.
Recommended talk (English): Kavya Joshi on locks — embedded below.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
