Lecture 24: Synchronization
Section 1: Hardware Synchronization Primitives and Atomic Instructions
Cache coherence ensures that all cores eventually see a consistent view of any single memory address, and shared memory lets threads read and write common variables freely. Yet coherence alone is not enough to coordinate which thread owns a shared data block at any instant.
Suppose Core A and Core B both want exclusive ownership of a shared data block protected by a lock variable b (0 = not locked, 1 = locked). Without hardware synchronization support, each processor tries to test if lock == 0 and, if so, write lock = 1 using ordinary load and store instructions. Look at what fails when Core A and Core B request the lock concurrently:
- Core A executes
load band seeslock == 0. - At the same moment, Core B executes
load band also seeslock == 0. - Both cores conclude the lock is free and execute
store b, 1! Now both cores believe they hold the exclusive lock, corrupting the shared data.
To fix this race condition, hardware must provide a primitive capable of atomically reading and modifying a memory location as one indivisible step so no other core can intervene between the read and the write.
Single-Instruction Hardware Atomics
Architectures provide several classic single-instruction atomic primitives:
- Atomic Exchange (
EXCH): Atomically swaps a value in a CPU register with a value in memory. Suppose Core A wants to acquire or release a remote lock bit initialized to0(1 = locked):- Core A puts
1, Remote lock bit is0: Core A gets0, remote becomes1. Core A sees it received0and now owns the lock. - Core A puts
1, Remote lock bit is1: Core A gets1, remote stays1. No change (someone else already owns the lock; Core A must retry). - Core A puts
0, Remote lock bit is1: Core A gets1, remote becomes0. Unlocked. - (Putting
0when the remote lock bit is already0is an invalid/unused state when releasing a held lock.)
- Core A puts
- Test-and-Set: Atomically tests a condition on a memory word (e.g., whether it equals
0) and sets the lock (1) if the condition passes. - Fetch-and-Increment: Atomically returns the current value of a memory location and increments it in memory.
- Compare-and-Swap (
cas R1, R2, M): Atomically compares registerR1with memory locationM; if and only if they are equal, exchangesR2withM.
Two-Instruction Atomics: Load Linked / Store Conditional (LL/SC)
A student might wonder: Why not just put EXCH or CAS into every RISC ISA? Think about implementing a single atomic read-modify-write instruction inside an out-of-order, multi-level cache hierarchy! One instruction has to read an address, perform an ALU operation or comparison, and write back to the same cache line—while blocking every other core’s coherence requests from touching that line in between, creating ugly pipeline and bus-locking complexity.
Instead, architectures like MIPS (and RISC-V’s LR/SC) split the atomic into two separate instructions, where the second instruction returns a flag telling software whether the pair actually executed atomically:
LL(Load Linked): Loads and returns the initial value at the memory address, while setting an internal hardware link/reservation watching that address.SC(Store Conditional): Attempts to write a new value to that same address and returns1if it succeeded or0if it failed:- If the content (or coherence ownership) of the location read by
LLchanges beforeSCexecutes \impliesSCfails (returns0). - If the processor context switches (or takes an interrupt) between
LLandSC\impliesSCfails (returns0).
- If the content (or coherence ownership) of the location read by
Worked Examples: Building Atomics with LL/SC
Watch how easily we construct both Atomic Exchange and Fetch-and-Increment out of LL and SC:
Atomic Exchange (atomically swap register
R4with memory location0(R1)):try: mov R3, R4 # Copy desired new value into R3 (R3 gets overwritten by SC!) ll R2, 0(R1) # R2 = old value in memory; set reservation sc R3, 0(R1) # Try to store R3 into 0(R1); R3 = 1 (success) or 0 (fail) beqz R3, try # If SC failed (R3 == 0), retry from the top mov R4, R2 # R4 = old memory valueNotice why
mov R3, R4must sit inside thetry:loop:scoverwritesR3with the0/1status code, so on a failed attemptR3is0and must be reloaded fromR4before retrying. At the end,R4and0(R1)have been atomically exchanged!Atomic Fetch-and-Increment (return old value in
R2and increment0(R1)):try: ll R2, 0(R1) # R2 = current counter value addi R3, R2, #1 # R3 = R2 + 1 sc R3, 0(R1) # Try to store R2 + 1 beqz R3, try # Retry if another core or context switch interfered
[Editor Note: removed course title slide.]
✎ Check Your Understanding
Why do two concurrent cores executing ordinary
loadfollowed bystorefail to implement a mutex lock? Answer: Both cores can executeloadconcurrently, observelock == 0, and then both executestore 1, leaving both cores believing they acquired the lock.In an
LL/SCsequence, name the two conditions that causeSCto fail (return0) and force software to retry. Answer:SCfails if the memory location read byLLis modified (or loses coherence ownership) beforeSCexecutes, or if the processor context-switches betweenLLandSC.
Section 2: Software Spin Locks, Cache Coherence Traffic, and Scalable Locks
Now that we have hardware atomics, how do we build a lock in software? The simplest design is a spin lock, where a waiting core repeatedly loops (“spins”) trying to acquire the lock until the current owner releases it (0):
addi R2, R0, #1
lockit: EXCH R2, 0(R1) ; atomic exchange
bnez R2, lockit ; if old value != 0, already locked -> retry
A spin lock grabs the lock immediately after it is freed (with no OS context-switch latency), at the cost of tying up the spinning processor. If there is no cache coherence and the lock sits in shared memory, this tight EXCH loop works reasonably well.
Why Naive Spin Locks Break Under Cache Coherence
Look at what happens when we run that exact EXCH spin loop on top of a cache-coherent multiprocessor (as developed earlier):
- An atomic write (
EXCH) cannot complete until the cache line transitions from Shared (S) to Modified (M). - That means every single iteration of
EXCHby every waiting core sends a write-invalidation across the bus, invalidating everyone else’s copy of the lock! - Every invalidated waiter immediately suffers a cache miss and goes back to the bus to reload the lock, generating a continuous storm of bus/directory traffic even while the lock stays
1!
Solution: Test and Test-and-Set
We eliminate the spinning invalidation traffic by separating reading from attempting the atomic write:
lockit: ld R2, 0(R1) ; read lock locally in Shared cache state
bnez R2, lockit ; spin locally in cache without bus traffic!
addi R2, R0, #1
EXCH R2, 0(R1) ; lock looked free (0) -> try atomic exchange
bnez R2, lockit ; lost the race -> go back to read-spinning
(With LL/SC, the exact same pattern is lockit: ll R2, 0(R1); bnez R2, lockit; addi R2, R0, #1; sc R2, 0(R1); beqz R2, lockit—and using CAS, you simply ld until 0 and then execute cas expecting 0 to swap in 1.)
As long as the lock stays 1, every waiting processor spins on ld inside its own local cache in the Shared state, producing zero bus traffic!
Worked Trace: Three Processors Contending on Test and Test-and-Set
Let’s trace 3 processors (P0, P1, P2) executing this Test and Test-and-Set loop step-by-step:
- Step 1:
P0holds the lock (1).P1andP2each miss once, load1, and begin spinning locally onld, testing iflock == 0(SharedacrossP0, P1, P2). - Step 2:
P0releases the lock by writing0. The bus sends write-invalidates toP1andP2(ExclusiveatP0). - Step 3:
P1andP2both suffer cache misses. The bus/directory servicesP2’s read miss first (P0writes back0; state becomesShared). - Step 4:
P2’slock == 0test succeeds! (P1waits while the bus is busy.) - Step 5: The bus services
P1’s read miss (Shared);P1’slock == 0test also succeeds! - Step 6: Both
P1andP2executeEXCH!P2wins the bus, generates an invalidate (invalidatingP1), receives0, and setslock = 1(ExclusiveatP2). - Step 7:
P2enters its critical section! Now the bus servicesP1’sEXCHmiss, sending an invalidate toP2and forcingP2to write back1(ExclusiveatP1).P1’s swap returns1(already locked!) and writes1. - Step 8:
P1seesR2 != 0and goes back to spinning locally onld!
The Scalability Problem and Two Fixes: Backoff and Ticket Locks
Notice what happens in Steps 2–7 above when many processors (N) are waiting on one lock:
- Owner releases lock \implies invalidates all N waiters.
- All N waiters read-miss and fetch
0. - All N waiters rush to execute
EXCHsimultaneously. - One winner acquires the lock and invalidates the other N-1 losers, who repeat the storm! Spin locks are not scalable—every lock handoff triggers O(N^2) coherence traffic across N waiters.
Two software improvements address this contention:
Spin Lock with Exponential Backoff: When a thread fails to acquire the lock, wait a bit before retrying, doubling (
sll R3, R3, 1) the delay on each failure:li R3, 1 ; initial delay lockit: ll R2, 0(R1) bnez R2, lockit ; spin locally while locked addi R2, R2, #1 ; R2 was 0 -> R2 = 1 sc R2, 0(R1) bnez R2, gotit ; SC succeeded (returned 1)! sll R3, R3, 1 ; SC failed -> double delay pause R3 ; wait R3 cycles j lockit gotit:Exponential backoff sharply reduces bus traffic and network contention—but comes with bad news: unfairness (starvation). A newly arriving thread has a tiny delay (
1) and can repeatedly snatch the lock away from an older thread stuck sleeping for a huge exponential delay!Ticket Locks (Scalable + Strictly Fair): To achieve both low contention and strict FIFO fairness, a Ticket Lock maintains two shared counters initialized to
0:next_ticket(enqueue ticket) andnow_serving(dequeue ticket).void ticketLock_acquire(int *next_ticket, int *now_serving) { int my_ticket = fetch_and_inc(next_ticket); // Atomically take a ticket while (*now_serving != my_ticket) {} // Spin locally until called } void ticketLock_release(int *now_serving) { (*now_serving)++; // Serve next ticket in line }Worked Example (
P0, P1, P2):P0arrives first, receivesmy_ticket = 0(next_ticketbecomes1), seesnow_serving == 0, and enters its critical section immediately.P1arrives and receivesmy_ticket = 1(next_ticketbecomes2);P2arrives and receivesmy_ticket = 2(next_ticketbecomes3). Both spin locally readingnow_serving(0).- When
P0finishes, it incrementsnow_servingto1:P1(and onlyP1) enters next—no stampede ofEXCHinstructions, and zero starvation! WhenP1releases,now_servingbecomes2, andP2enters.
✎ Check Your Understanding
Why does spinning on an ordinary
ldbefore attemptingEXCH(Test and Test-and-Set) drastically reduce bus traffic compared to spinning directly onEXCH? Answer: Becauseldhits locally in the cache’sSharedstate without touching the bus, whereasEXCHis a write that forces anS -> Minvalidation onto the bus on every single spin iteration.What flaw in an exponential-backoff spin lock does a Ticket Lock solve, and how? Answer: Exponential backoff is unfair (newcomers with short backoffs can starve long-waiting threads). A Ticket Lock guarantees strict FIFO fairness by giving each arriving thread a unique sequential number via
fetch_and_inc(next_ticket)and serving threads strictly in order vianow_serving.
Section 3: Barrier Synchronization — Sense Reversal and Combining Trees
Mutex locks protect critical sections so only one thread enters at a time. A Barrier solves the opposite coordination problem: force all P processes to wait until every process reaches the barrier, and then release all of them together (for example, between time steps of a physics simulation).
A Naive Barrier—and Its Subtle Deadlock Bug
A simple centralized barrier uses one shared counter (count) and two spin flags/locks: counterlock (protecting count) and release (holding waiters until the last process arrives):
lock(counterlock);
if (count == 0) release = 0; /* First process: reset release flag */
count++; /* Record arrival */
unlock(counterlock);
if (count == total) { /* Last process arrived! */
count = 0;
release = 1; /* Release waiting processes */
} else {
spin(release == 1); /* Spin until release = 1 */
}(Wait: notice that reading count == total outside counterlock works only if checked inside or before count is reset; even assuming that’s protected inside the lock, there is a far deadlier bug here!)
What goes wrong when this barrier is used inside a loop? Suppose all total processes arrive, the last process sets count = 0; release = 1;, and the waiting processes begin waking up. Suppose that before the slowest waiting process reads release == 1 and leaves the barrier, the fastest process finishes the next phase of work, loops around, arrives at the barrier again, sees count == 0, and sets release = 0!
- The slow process from the previous barrier sees
release == 0again and never leaves! - Because the slow process never leaves,
countfor the second barrier never reachestotal! - The entire program deadlocks and spins forever!
Solution: The Sense-Reversing Barrier
To prevent a fast thread from resetting the flag under a slow thread’s feet, we use a Sense-Reversing Barrier. Each process keeps a private variable local_sense initialized to 1, which toggles (0 \leftrightarrow 1) at every barrier crossing to control the direction of the barrier:
local_sense = !local_sense; /* Toggle private sense (0, then 1, then 0...) */
lock(counterlock);
count++; /* Increment arrival count */
int my_count = count; /* Capture count safely under lock */
unlock(counterlock);
if (my_count == total) { /* All have arrived */
count = 0;
release = local_sense; /* Flip global release to match this barrier's sense */
} else {
spin(release == local_sense); /* Wait until release equals this barrier's sense */
}Trace why the deadlock vanishes: on barrier #1, every thread sets local_sense = 0 and waits for release == 0. When the last thread sets release = 0, even if a fast thread immediately loops around to barrier #2, that fast thread toggles its private local_sense to 1 and spins waiting for release == 1—it never touches release until all threads (including the slow thread from barrier #1!) arrive at barrier #2!
Eliminating the Counter Lock and Scaling Barriers
Notice two performance improvements for large-scale barriers:
Fetch-and-Increment Barrier: Instead of acquiring and releasing
counterlockaroundcount++, each arriving process simply executes an atomicfetch&inc(count)—eliminatingcounterlockentirely!local_sense = !local_sense; int my_count = fetch_and_inc(count); /* Atomic increment, returns old count */ if (my_count + 1 == total) { /* Last thread to arrive */ count = 0; release = local_sense; } else { spin(release == local_sense); }Combining Tree Barrier: On a machine with hundreds of cores, having every core spin-increment one central
countvariable generates a massive storm of coherence traffic on the bus/interconnect. A Combining Tree Barrier distributes arrival counting across a tree of nodes, where each node has a localcounterlock,count,parentindex (-1at the root), and fan-in k:void Barrier(int mynode) { lock(tree[mynode].counterlock); tree[mynode].count++; unlock(tree[mynode].counterlock); if (tree[mynode].count == k) { /* All k children/threads arrived at mynode */ tree[mynode].count = 0; /* Reset local node count for next time */ if (tree[mynode].parent >= 0) Barrier(tree[mynode].parent); /* Propagate upward to parent */ else release = local_sense; /* Arrived at root -> release everyone! */ } else { spin(release == local_sense); /* Wait for global release */ } }Each leaf node absorbs k local arrivals and sends only one signal upward to the next level of the tree, reducing contention by a factor of k at every level until the single last thread reaches the root and flips
release.
[Editor Note: removed acknowledgements slide.]
✎ Check Your Understanding
Explain the race condition that causes a naive barrier (resetting
release = 0on first arrival) to deadlock when called repeatedly in a loop. Answer: If one fast thread exits the first barrier, completes its work, and enters the second barrier before a slow thread has noticedrelease == 1and exited the first barrier, the fast thread resetsrelease = 0—trapping the slow thread in the first barrier forever.How does a Combining Tree Barrier with fan-in k reduce interconnect contention on a large multiprocessor? Answer: Instead of all N processors atomically incrementing one central counter, groups of k threads synchronize on local leaf nodes, and only the k-th thread at each node advances to the parent, reducing contention hierarchically.