13. Thread-Level Parallelism: Multicore, Synchronization, Coherence, Consistency
Description
TLP runs multiple threads or processes at once. It became the main route to performance once single-core clock speed and ILP stopped scaling.
Process vs thread:
| Process | Thread | |
|---|---|---|
| Address space | Own, isolated | Shared with other threads of the same process |
| Creation / switch cost | Heavy | Light |
| Communication | IPC (pipes, sockets, shared memory) | Direct shared variables (needs synchronization) |
| Failure isolation | Strong | One bad thread can crash the whole process |
| Example | Browser and text editor | Browser tabs as threads of one process |
Multicore and SMP: a multicore chip puts several cores on one die. In a symmetric multiprocessor (SMP) all processors have equal (uniform) access to shared memory (UMA). Larger machines use NUMA (non-uniform memory access): each socket has local memory that is faster than remote memory. Two programming models: shared memory (threads, pthreads, OpenMP) and message passing (MPI).
Why more cores don't give linear speedup: serial fractions (Amdahl), synchronization waits, memory-bandwidth contention, load imbalance and communication.
Synchronization: controlling access to shared data.
- Race condition: result depends on timing of unsynchronized accesses.
- Mutex/lock: only one thread in the critical section.
- Atomic primitives: test-and-set, compare-and-swap (CAS), load-linked/store-conditional (LL/SC), fetch-and-add.
- Barrier: all threads wait until all arrive.
- Deadlock: threads wait on each other forever.
Cache coherence: each core has private caches, so several copies of one memory block can exist; coherence makes sure all cores see one consistent value per location. Two approaches:
- Snooping (bus-based): every cache watches (snoops) bus transactions. Good for small core counts.
- Directory-based: a directory tracks which caches hold each block; scalable to many cores.
Two write strategies: write-invalidate (a writer invalidates other copies; the common choice) and write-update.
MESI protocol (Papamarcos & Patel, 1984): each cache line is in one of four states.
| State | Meaning | Memory up to date? | Other caches may hold it? |
|---|---|---|---|
| Modified | Only copy, dirty | No | No |
| Exclusive | Only copy, clean | Yes | No |
| Shared | Clean, possibly in several caches | Yes | Yes |
| Invalid | Not usable | n/a | n/a |
Coherence misses: true sharing (threads genuinely share a word) and false sharing (different variables on the same cache line cause needless invalidations).
Memory consistency model: defines the order in which memory operations of different threads may appear to others (coherence is per location, consistency is across locations).
- Sequential consistency (SC): as if all operations ran in one global order that respects each thread's program order (Lamport 1979). Simple but slow to implement.
- TSO (total store order, x86): stores may be delayed in a store buffer, so a later load can pass an earlier store.
- Relaxed / weak models (ARM, RISC-V RVWMO, Power): most reorderings allowed unless you insert fences or use acquire/release operations.
Multithreading performance: limited by lock contention, false sharing and bandwidth. SMT (Topic 11) adds hardware threads inside a core.
Key Formulas
Amdahl (n cores): S(n) = 1 / [ (1 − f) + f / n ]
Gustafson (scaled work): S(n) = s + n · (1 − s) (s = serial fraction of the PARALLEL run)
Parallel efficiency: E(n) = S(n) / n
Directory storage (full bit-vector) per block = (number of cores) bits (+ state)
overhead % = cores / (block size in bits)
Probability false sharing hurts: any write to a shared line invalidates all other copies
Steps
Protect a shared counter: (1) identify the shared variable, (2) acquire a lock (or use an atomic add), (3) update, (4) release.
MESI on a read miss: (1) issue bus read, (2) if another cache holds the block in M, it supplies the data and writes it back, state becomes S in both, (3) if others hold it in S/E → requester gets S, (4) if nobody has it → requester gets E.
MESI on a write: (1) if the line is M → write locally, (2) if E → silently change to M (no bus traffic), (3) if S → broadcast invalidate/upgrade, then M, (4) if I → read-for-ownership, other copies become I, then M.
Worked Example
A. Amdahl vs Gustafson. Serial fraction 5%, 64 cores.
- Amdahl (fixed problem size): 1 / (0.05 + 0.95/64) = 15.4.
- Gustafson (problem grows with machine): 0.05 + 64 × 0.95 = 60.85.
Which one applies depends on whether the workload is fixed or scales with the hardware.
B. MESI trace (two cores, one block X, initially only in memory).
| Step | Event | Core 0 | Core 1 | Bus / memory action |
|---|---|---|---|---|
| 1 | C0 reads X | E | I | BusRd, memory supplies, no sharers |
| 2 | C1 reads X | S | S | BusRd, both now share |
| 3 | C0 writes X | M | I | Upgrade/invalidate C1's copy |
| 4 | C1 reads X | S | S | C0 supplies data, writes back to memory |
| 5 | C1 writes X | I | M | C0 invalidated |
A core that reads a private block (E) and then writes it moves E → M with no bus traffic.
C. False sharing. Two threads increment counter[0] and counter[1] (two 8-byte longs) that sit in the same 64 B line. Each write invalidates the other core's copy, so the line ping-pongs between caches and both threads slow down dramatically. Fix: pad each counter to its own 64 B line.
D. Memory-consistency litmus test (store buffering). Initially x = y = 0.
Thread 0: x = 1; r1 = y; Thread 1: y = 1; r2 = x;
- Sequential consistency forbids r1 = 0 and r2 = 0.
- TSO (x86) and relaxed models allow it, since each store may still be in a store buffer when the other thread loads.
- Fix: put a full fence between the store and the load in each thread.
E. Directory overhead. 64 cores, 64-byte (512-bit) blocks: full bit-vector = 64 bits per block → 64/512 = 12.5% extra storage; it grows linearly with core count, which is why large systems use coarser sharer encodings.
Python / Assembly
class MESI:
def __init__(self, n): self.s = ['I'] * n
def read(self, c):
if self.s[c] != 'I': return 'hit'
others = [o for o in range(len(self.s)) if o != c and self.s[o] != 'I']
for o in others: self.s[o] = 'S' # an M copy is written back here
self.s[c] = 'S' if others else 'E'
return 'BusRd'
def write(self, c):
if self.s[c] == 'M': return 'hit'
if self.s[c] == 'E': self.s[c] = 'M'; return 'silent E->M'
for o in range(len(self.s)):
if o != c: self.s[o] = 'I'
self.s[c] = 'M'; return 'BusRdX/Upgrade'
m = MESI(2)
for who, op in [(0,'r'), (1,'r'), (0,'w'), (1,'r'), (1,'w')]:
print(who, op, m.read(who) if op == 'r' else m.write(who), m.s)
# 0 r BusRd ['E','I'] | 1 r BusRd ['S','S'] | 0 w BusRdX/Upgrade ['M','I']
# 1 r BusRd ['S','S'] | 1 w BusRdX/Upgrade ['I','M']
Protecting shared data with a lock (race conditions may not appear on every run, but the lock is what makes the result guaranteed):
import threading
counter, lock = 0, threading.Lock()
def work(n):
global counter
for _ in range(n):
with lock: # critical section
counter += 1
ts = [threading.Thread(target=work, args=(100_000,)) for _ in range(4)]
[t.start() for t in ts]; [t.join() for t in ts]
print(counter) # always 400000
RISC-V spinlock using an atomic swap, with acquire/release ordering:
# a0 = address of lock word (0 = free, 1 = held)
acquire:
li t0, 1
again:
amoswap.w.aq t1, t0, (a0) # atomically swap in 1, get old value (acquire)
bnez t1, again # old value was 1 -> someone holds it, retry
# ---- critical section ----
release:
amoswap.w.rl x0, x0, (a0) # write 0 (release)
Compare-and-swap built from LR/SC (a1 = expected, a2 = new value):
cas:
lr.w t0, (a0) # load-reserved
bne t0, a1, fail # value differs -> CAS fails
sc.w t1, a2, (a0) # store-conditional (t1 = 0 on success)
bnez t1, cas # reservation lost -> retry
fail:
Ordering with fences (store-buffering fix and producer/consumer):
# store-buffering fix, thread 0: # producer / consumer:
sw t0, 0(a0) # x = 1 # producer: sw a2, 0(a0) # data
fence rw, rw # full fence fence w, w
lw t1, 0(a1) # r1 = y sw t0, 0(a1) # flag = 1
# consumer: spin: lw t1, 0(a1); beqz t1, spin
# fence r, r; lw a3, 0(a0)
Notes
- Common mistake: ARM and x86 are not both weakly consistent. x86 uses TSO, a relatively strong model; ARM and RISC-V are the genuinely weak/relaxed ones.
- MESI example: a core that updates a value notifies the others, which invalidate their copies.
- Python threads do not give CPU parallelism (GIL); the lock example is about correctness, not speed.
- Use thread-local data and reduce sharing; padding and alignment avoid false sharing.
- Core count has limits: bandwidth, power and software scalability, not just transistor budget.
- Quick facts: processes have separate address spaces, threads share one; SMP processors share memory equally; coherence keeps cached data consistent; MESI protocol; relaxed consistency allows reordering for speed.
References: [HP6] Ch. 5 (5.1-5.7: centralized/distributed shared memory, synchronization, memory consistency); [PH-RV] Ch. 6 (6.5 shared-memory multiprocessors, 6.10), Ch. 5 (5.10 cache coherence); Papamarcos & Patel, "A Low-Overhead Coherence Solution for Multiprocessors with Private Cache Memories," ISCA 1984; Lamport, "How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs," IEEE Trans. Computers, 1979; [RV-Spec] Vol. I ("A" extension, memory model);
All rights remain with the original author (Algo-holics). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me