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:

  1. Core A executes load b and sees lock == 0.
  2. At the same moment, Core B executes load b and also sees lock == 0.
  3. 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:

  1. 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 to 0 (1 = locked):
    • Core A puts 1, Remote lock bit is 0: Core A gets 0, remote becomes 1. Core A sees it received 0 and now owns the lock.
    • Core A puts 1, Remote lock bit is 1: Core A gets 1, remote stays 1. No change (someone else already owns the lock; Core A must retry).
    • Core A puts 0, Remote lock bit is 1: Core A gets 1, remote becomes 0. Unlocked.
    • (Putting 0 when the remote lock bit is already 0 is an invalid/unused state when releasing a held lock.)
  2. 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.
  3. Fetch-and-Increment: Atomically returns the current value of a memory location and increments it in memory.
  4. Compare-and-Swap (cas R1, R2, M): Atomically compares register R1 with memory location M; if and only if they are equal, exchanges R2 with M.

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:

Worked Examples: Building Atomics with LL/SC

Watch how easily we construct both Atomic Exchange and Fetch-and-Increment out of LL and SC:

  1. Atomic Exchange (atomically swap register R4 with memory location 0(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 value

    Notice why mov R3, R4 must sit inside the try: loop: sc overwrites R3 with the 0/1 status code, so on a failed attempt R3 is 0 and must be reloaded from R4 before retrying. At the end, R4 and 0(R1) have been atomically exchanged!

  2. Atomic Fetch-and-Increment (return old value in R2 and increment 0(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

  1. Why do two concurrent cores executing ordinary load followed by store fail to implement a mutex lock? Answer: Both cores can execute load concurrently, observe lock == 0, and then both execute store 1, leaving both cores believing they acquired the lock.

  2. In an LL/SC sequence, name the two conditions that cause SC to fail (return 0) and force software to retry. Answer: SC fails if the memory location read by LL is modified (or loses coherence ownership) before SC executes, or if the processor context-switches between LL and SC.


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):

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:

  1. Step 1: P0 holds the lock (1). P1 and P2 each miss once, load 1, and begin spinning locally on ld, testing if lock == 0 (Shared across P0, P1, P2).
  2. Step 2: P0 releases the lock by writing 0. The bus sends write-invalidates to P1 and P2 (Exclusive at P0).
  3. Step 3: P1 and P2 both suffer cache misses. The bus/directory services P2’s read miss first (P0 writes back 0; state becomes Shared).
  4. Step 4: P2’s lock == 0 test succeeds! (P1 waits while the bus is busy.)
  5. Step 5: The bus services P1’s read miss (Shared); P1’s lock == 0 test also succeeds!
  6. Step 6: Both P1 and P2 execute EXCH! P2 wins the bus, generates an invalidate (invalidating P1), receives 0, and sets lock = 1 (Exclusive at P2).
  7. Step 7: P2 enters its critical section! Now the bus services P1’s EXCH miss, sending an invalidate to P2 and forcing P2 to write back 1 (Exclusive at P1). P1’s swap returns 1 (already locked!) and writes 1.
  8. Step 8: P1 sees R2 != 0 and goes back to spinning locally on ld!

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:

  1. Owner releases lock \implies invalidates all N waiters.
  2. All N waiters read-miss and fetch 0.
  3. All N waiters rush to execute EXCH simultaneously.
  4. 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:

  1. 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!

  2. 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) and now_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):

    • P0 arrives first, receives my_ticket = 0 (next_ticket becomes 1), sees now_serving == 0, and enters its critical section immediately.
    • P1 arrives and receives my_ticket = 1 (next_ticket becomes 2); P2 arrives and receives my_ticket = 2 (next_ticket becomes 3). Both spin locally reading now_serving (0).
    • When P0 finishes, it increments now_serving to 1: P1 (and only P1) enters next—no stampede of EXCH instructions, and zero starvation! When P1 releases, now_serving becomes 2, and P2 enters.

✎ Check Your Understanding

  1. Why does spinning on an ordinary ld before attempting EXCH (Test and Test-and-Set) drastically reduce bus traffic compared to spinning directly on EXCH? Answer: Because ld hits locally in the cache’s Shared state without touching the bus, whereas EXCH is a write that forces an S -> M invalidation onto the bus on every single spin iteration.

  2. 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 via now_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!

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:

  1. Fetch-and-Increment Barrier: Instead of acquiring and releasing counterlock around count++, each arriving process simply executes an atomic fetch&inc(count)—eliminating counterlock entirely!

    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);
    }
  2. Combining Tree Barrier: On a machine with hundreds of cores, having every core spin-increment one central count variable 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 local counterlock, count, parent index (-1 at 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

  1. Explain the race condition that causes a naive barrier (resetting release = 0 on 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 noticed release == 1 and exited the first barrier, the fast thread resets release = 0—trapping the slow thread in the first barrier forever.

  2. 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.