---
title: Memory consistency and synchronization
heading: Sequential consistency, store buffers and TSO, relaxed models and fences, atomics, locks and barriers
eyebrow: S4 · Lesson 35 · Memory consistency and synchronization
xp: 50
---

::: hook
Coherence makes every core agree on the history of each single address. It says nothing about the order in which a core's writes to *different* addresses become visible to others, and that's where parallel programs break. On a real x86 machine, two threads that each set their own flag and then read the other's can both see the other's flag still clear, an outcome impossible if memory operations happened one at a time in program order. The memory consistency model is the contract that says which outcomes are allowed; fences and atomic instructions are how programs ask for more order than the hardware gives by default, and locks and barriers are built from them.
:::

::: play
- Coherence transactions until each of N contending cores has held a lock once, on log scales. Test-and-test-and-set (solid): every waiter misses twice at each release, N(N − 1) in all. Ticket lock (dashed): once per waiter, half that. Queue (MCS) lock: one transaction per handoff, N − 1.
- The first two grow with the square of the core count, so a lock that's fine on 4 cores can swamp the interconnect on 64.
- The program at the heart of the lesson is below: thread 1 runs `x = 1; r1 = y` and thread 2 runs `y = 1; r2 = x`, with x and y starting at 0.
:::
:::

```sim plot
view: graph
x: N = 2..256 log
y: T = 1..100000 log
plot: N*(N - 1) | samples: 300 | label: test-and-test-and-set
plot: N*(N - 1)/2 | samples: 300 | dashed | color: ch2 | label: ticket lock
plot: N - 1 | samples: 300 | dashed | color: ch3 | label: queue (MCS) lock
```

::: predict
## In the program above, which outcomes can sequential consistency produce?

- [ ] Only (1, 1)
- [x] (0, 1), (1, 0) and (1, 1), but never (0, 0)
- [ ] All four, including (0, 0)
- [ ] Only (0, 0)

::: reveal
Under SC, operations from both threads interleave in some single order that respects each thread's program order. Whichever store comes first in that order is seen by the other thread's later load, so at least one of r1 and r2 is 1: (0, 1), (1, 0) or (1, 1). Under TSO each store can sit in its core's store buffer while the following load reads memory, so (0, 0) appears too, and Dekker's mutual-exclusion algorithm fails without a fence.
:::
:::

::: nameit
## Store buffers and the flag example

In the program above, under sequential consistency some write must come first, so (r1, r2) = (0, 0) is impossible. With a store buffer, each core's store waits in the buffer while its load runs ahead, so both loads can read 0. A fence between each store and the following load forces the buffer to drain first and restores the SC outcomes.

## Consistency models

- **Sequential consistency (SC):** the result is as if all operations ran in some single order that respects every thread's program order. Simple, but it forbids store buffers and most reordering.
- **Total store order (TSO, x86):** a store may be delayed past later loads (to different addresses) via the store buffer; all other orders are kept.
- **Relaxed models (ARM, RISC-V RVWMO, POWER):** loads and stores to different addresses may be reordered in most ways; programs insert **fences** or use **acquire** and **release** operations where order matters.
- **Data-race-free guarantee:** a program whose shared accesses are all ordered by synchronization behaves as if sequentially consistent on all these models. Languages (C++, Java) build on that.

## Atomics

- **Test-and-set, swap, fetch-and-add, compare-and-swap (CAS):** read-modify-write instructions the coherence protocol performs atomically, by holding the line in M state.
- **Load-reserved / store-conditional (RISC-V lr/sc, ARM ldxr/stxr):** the store succeeds only if no other core wrote the line since the load, so a retry loop builds any atomic operation.

## Locks and their traffic

- **Test-and-set spin lock:** every attempt writes, so waiters keep stealing the line from each other.
- **Test-and-test-and-set:** waiters spin reading their cached copy; a release invalidates all of them, and each then misses and tries to set: about two transactions per waiter per handoff.
- **Ticket lock:** a release makes each waiter reread the "now serving" counter: one miss per waiter per handoff, and FIFO fairness.
- **Queue (MCS) locks:** each waiter spins on its own flag; a handoff touches one line.

A lock held for a fraction c of each thread's time limits the whole program to at most 1/c threads' worth of throughput (Amdahl's law with the critical section as the serial part).

## Barriers

A **centralized** barrier counts arrivals with fetch-and-add: N serialized atomic operations. A **tree** barrier with fan-in k combines arrivals in $\lceil\log_kN\rceil$ levels.
:::

::: example
## N cores contend for a test-and-test-and-set lock: one holds it and N − 1 wait. Each release makes every waiting core miss twice (a read, then its test-and-set), and one fewer core waits after each handoff. How many transactions until everyone has had the lock, for N = 8 and N = 64? What would an MCS lock need?

::: solution
1. **Test-and-test-and-set.** Handoffs see N − 1, N − 2, …, 1 waiters:
   $$2\sum_{k=1}^{N-1}k = N(N - 1)$$
   which is 56 for N = 8 and 4032 for N = 64.
2. **Ticket lock.** It halves that (one miss per waiter): 28 and 2016.
3. **MCS lock.** It needs one handoff transaction per release: 7 and 63.
4. **Why it matters.** The quadratic growth is why scalable systems use queue locks.

**Answer:** 56 transactions for N = 8 and 4032 for N = 64; an MCS lock needs only 7 and 63.
:::
:::

::: example
## Threads spend 5% of their time in a critical section protected by one lock. What's the best throughput with any number of threads? And how long does a 1024-thread barrier take as a tree with fan-in 4, at 50 ns per level, against a centralized counter at 30 ns per atomic?

::: solution
1. **Lock limit.** At most
   $$1/0.05 = 20$$
   threads' worth of throughput, however many threads run.
2. **Tree barrier depth.**
   $$\lceil\log_4 1024\rceil = 5\ \text{levels}$$
   so 250 ns per arrival wave, and as much again to release.
3. **Centralized counter.**
   $$1024 \times 30\ \text{ns} = 30.7\ \text{µs}$$

**Answer:** the best throughput is 20 threads' worth; the tree barrier takes 250 ns per wave against 30.7 µs for the centralized counter.
:::
:::

::: example
## Sixty-four cores queue on a ticket lock. Each handoff makes every remaining waiter reread the "now serving" counter once. How many misses until all have had the lock, and how many with an MCS lock?

::: solution
1. **Ticket lock.** With w waiters, a handoff costs w misses; summing w from 63 down to 1 gives
   $$64 \times 63/2 = 2016\ \text{misses}$$
2. **MCS lock.** It hands off by writing one waiter's own flag: 63 transfers in all.
3. **Why it matters.** At large core counts the queue lock's linear traffic is the difference between a lock that scales and one that doesn't.

**Answer:** 2016 misses with the ticket lock, and 63 transfers with an MCS lock.
:::
:::

::: check
kind: choice

## On a TSO machine (x86), which of these reorderings can a program observe?

- [ ] A load passing an earlier load
- [x] A load passing an earlier store to a different address
- [ ] A store passing an earlier store
- [ ] A store passing an earlier load

::: right
Right. TSO keeps every order except store-then-load, which the store buffer relaxes.
:::

::: misses
- [1] TSO keeps loads in order.
- [3] Stores leave the store buffer in order, so TSO keeps stores in order.
- [4] TSO doesn't let a store become visible before an earlier load.
:::
:::

::: check
kind: choice

## Which instruction sequence lets a thread atomically add to a shared counter on RISC-V without a lock?

- [ ] A load, an add and a store
- [ ] A fence, then a load, an add and a store
- [x] lr.w, add, sc.w, retrying if the sc fails
- [ ] Two loads to check the value hasn't changed, then a store

::: right
Right. The store-conditional fails if another core wrote the line since the load-reserved, so the loop retries until the read-modify-write happened without interference.
:::

::: misses
- [1] Another core can write between the load and the store, and one update is lost.
- [2] A fence orders this thread's accesses but doesn't stop another core writing in between.
- [4] Another core can still write between the check and the store.
:::
:::

::: check
given: N = 4 | 8 | 16 | 64
answer: N*(N - 1)
tolerance: 0

## {N} cores contend for a test-and-test-and-set lock, one holding it and the rest waiting. Each release makes every waiting core miss twice, and one fewer waits after each handoff. How many transactions until all have held it?

::: right
Right. $2\sum_{k=1}^{N-1}k = N(N - 1)$ = {answer}.
:::

::: misses
- [N*(N - 1)/2] Each waiter misses twice per handoff: a read, then a test-and-set.
- [2*(N - 1)] Every waiting core misses at every handoff, not only the winner.
- [any] Not yet. Sum the waiters over the handoffs, times two.
:::
:::

::: check
given: N = 8 | 32 | 128
answer: N*(N - 1)/2
tolerance: 0

## The same {N} cores use a ticket lock, where each release costs one miss per waiting core. How many transactions until all have held it?

::: right
Right. $\sum_{k=1}^{N-1}k$ = {answer}.
:::

::: misses
- [N*(N - 1)] One miss per waiter per handoff, not two.
- [N - 1] Every waiter rereads the counter at each release.
- [any] Not yet. Sum the waiters over the handoffs.
:::
:::

::: check
given: c = 0.01 | 0.04 | 0.1
answer: 1/c
tolerance: 0.5%

## Every thread spends {c} of its time holding one shared lock. At most how many threads' worth of throughput can the program reach?

::: right
Right. 1/c = {answer}.
:::

::: misses
- [1/(1 - c)] The lock serializes the critical sections: they're the serial fraction.
- [any] Not yet. The lock can be held only one thread at a time.
:::
:::

::: check
given: N = 64 | 1000 | 4096; k = 2 | 4 | 8; t = 20 | 60
answer: ceil(log(N - 0.5)/log(k))*t
unit: ns
tolerance: 0

## A tree barrier with fan-in {k} gathers {N} threads, taking {t} ns per level. How long does the arrival phase take?

::: right
Right. $\lceil\log_kN\rceil$ levels × {t} ns = {answer} ns.
:::

::: misses
- [N*t] That's a centralized counter, one arrival at a time.
- [any] Not yet. Count the levels.
:::
:::

::: check
kind: parts
given: c = 0.02 | 0.05 | 0.1; N = 64 | 1024; k = 2 | 4 | 8; t = 30 | 50

## Threads spend {c} of their time in one critical section; a barrier joins {N} threads.

::: part
answer: 1/c
tolerance: 0.5%

### What is the most throughput, in threads' worth, the lock allows?

::: misses
- [any] $1/c$.
:::
:::

::: part
answer: ceil(log(N)/log(k) - 1e-9)*t
unit: ns
tolerance: 0.5%

### How long does a tree barrier with fan-in {k} take, at {t} ns per level?

::: misses
- [any] $\lceil\log_kN\rceil$ levels.
:::
:::

::: part
answer: N*t
unit: ns
tolerance: 0.5%

### And a centralized counter at {t} ns per atomic?

::: misses
- [any] N serialized atomics.
:::
:::
:::

::: check
kind: derivation
vars: N = 2..1024

## N cores contend for a lock until each has held it once.

::: step
answer: N*(N - 1)

### How many transactions does a test-and-test-and-set lock take (two per waiter per handoff)?
:::

::: step
answer: N*(N - 1)/2

### And a ticket lock (one per waiter per handoff)?
:::

::: step
answer: N - 1

### And an MCS queue lock (one per handoff)?
:::

::: right
Right. Quadratic traffic against linear: queue locks exist because of this sum.
:::
:::

::: explain
## Why does a store buffer break sequential consistency, and why do processors keep it anyway?

::: model
A store buffer lets a core put a store aside and keep executing instead of waiting for the store to reach the cache, which can take many cycles if the line has to be fetched or other copies invalidated. Meanwhile later loads to other addresses go ahead and read memory. To other cores, the store happens after those loads, so the core's operations appear out of program order, and outcomes like both threads reading 0 in the flag example become possible. Processors keep store buffers because stores are frequent and waiting for each one would cost a large fraction of performance, while correctly synchronized programs aren't affected: their fences and atomic operations drain the buffer exactly where order matters.
:::
:::

::: practice

::: check
given: N = 4 | 6 | 8 | 16 | 24 | 32
answer: N*(N - 1)
tolerance: 0

## Test-and-test-and-set transactions for {N} cores?

::: misses
- [any] $N(N - 1)$.
:::
:::

::: check
given: c = 0.01 | 0.02 | 0.04 | 0.05 | 0.08 | 0.1
answer: 1/c
tolerance: 0.5%

## Throughput limit with {c} in one critical section?

::: misses
- [any] 1/c.
:::
:::

::: check
given: N = 256 | 2000; k = 4 | 16; t = 30 | 80
answer: ceil(log(N - 0.5)/log(k))*t
unit: ns
tolerance: 0

## Tree barrier: {N} threads, fan-in {k}, {t} ns per level?

::: misses
- [any] $\lceil\log_kN\rceil t$.
:::
:::
:::
