Synchronization and Parallelism Atlas

Lectures 20 to 22 of 6.191: what goes wrong when several threads share memory, how semaphores fix it, how caches on different cores stay consistent, and how much speed more cores can actually buy. Each idea is shown as a flow diagram or a chart first. The detail and the code are folded underneath.

thread 1 / core 0thread 2 / core 1ModifiedSharedInvalid
About the sourceThe 6.191 slides for these lectures need an MIT login that was not available. This page teaches the standard material under the public lecture titles. Semaphore code is quoted from your lab7-yumelody/src/syscalls.c. Numbers such as buffer sizes and core counts are examples, not course parameters. Check notation against the slides before the exam, especially the names of bus messages.

0The big picture: five ideas

Idea 1 · Shared data plus interleaving gives answers that depend on timing

A statement like x = x + 1 is three machine steps. If another thread runs between them, one update overwrites the other.

A race condition exists when the result depends on the order in which threads happen to run. The bug is not in either thread alone. It is in the fact that a read-modify-write sequence was assumed to be indivisible and is not. This happens on one core too: a timer interrupt can switch processes between any two instructions.

Idea 2 · Make the sequence atomic and the timing stops mattering

A critical section is code that must not overlap with itself. Mutual exclusion lets one thread in at a time. Every interleaving then gives the same answer.

The general principle: you cannot control the scheduler, so restrict the set of interleavings to ones that are all correct. Locks shrink that set. They cost waiting time, so the critical section should hold only what truly needs protecting.

Idea 3 · A semaphore is a counter of permits

wait takes a permit and blocks if there is none. signal returns one and wakes a waiter. The initial value says how many may proceed, and that one number gives three different tools.

Initial value 1: mutex
wait(m)→critical section→signal(m)

One permit, so one thread inside. The same thread waits and signals.

Initial value N: resource count
permitpermitpermitN = 3

N identical resources, such as free buffer slots. The fourth requester blocks until one comes back.

Initial value 0: precedence
A; signal(s)→wait(s); B

No permit exists until A finishes, so B cannot start early. Different threads wait and signal.

Idea 4 · Many readers or one writer, never both

Each core has a private cache, so one memory line can exist as several copies. They stay consistent if, for every line, either several caches hold read-only copies or exactly one holds a writable copy.

Allowed: all copies identical
core 0
S
x = 5
core 1
S
x = 5
Allowed: one owner
core 0
M
x = 6, memory stale
core 1
I
no copy

The same rule appears as reader-writer locks in software and as the Lab 6 line statuses in hardware. NotValid, Clean and Dirty are Invalid, Shared and Modified with only one cache in the system.

Idea 5 · The serial part sets the ceiling

If a fraction p of the work can be spread over n cores, speed-up is 1 / ((1 − p) + p / n). As n grows this approaches 1 / (1 − p) and no further.

Tool

Amdahl's law

Run time on n cores, as a fraction of the one-core time

speed-up
limit with infinite cores
efficiency (speed-up / n)

This is the same reasoning as the performance equation in Lab 6: improving one term only helps in proportion to how much of the time that term accounts for.

1Lecture 20 · Synchronization

Try every interleaving yourself

Two threads each run x = x + 1 once. Choose which thread takes the next step. Find an order that ends with x = 1, then switch the semaphore on and try to break it.

Tool

Interleaving explorer

TermMeaning
ThreadAn independent sequence of execution with its own registers and stack. Threads of one process share memory.
Race conditionThe outcome depends on the relative timing of threads.
Critical sectionA region that reads and writes shared state and must run without overlap.
Mutual exclusionAt most one thread is in the critical section at any time.
AtomicAppears to happen all at once. No other thread can see a half-finished state.

Semaphores, as you built them in Lab 7

OperationDefinitionYour kernel
wait(s)If the value is above 0, decrement and continue. Otherwise block until a permit is available.Decrements, or sets blocked, records the semaphore in pid_waiting_for, and switches process
signal(s)Make one permit available. If a thread is blocked on s, wake one.If a process is waiting, unblocks it and does not increment. Otherwise increments

Producer and consumer with a bounded buffer

Two counting semaphores track what each side needs: free slots for the producer, filled slots for the consumer. Each side waits on its own resource and signals the other's.

Deadlock

Deadlock is a cycle of threads, each holding something the next one needs. Nobody is wrong locally and nobody can move.

Condition (all four are needed)MeaningHow to break it
Mutual exclusionThe resource cannot be sharedOften impossible to remove
Hold and waitA thread keeps what it has while asking for moreAcquire everything at once, or release and retry
No preemptionA resource cannot be taken awayTimeouts or rollback
Circular waitA cycle exists in the who-waits-for-whom graphGive locks a global order and always acquire in that order

Dining philosophers

Five philosophers sit in a ring with one fork between each pair. Each needs both neighbouring forks to eat. If everyone picks up the left fork first, all five hold one fork and wait forever for the right one. That is a five-way cycle.

The fix is the general one. Number the forks and always take the lower number first. P4 then reaches for f0 before f4, the same fork P0 takes first, so one of them blocks holding nothing and the cycle cannot close.

Recall

Why is x = x + 1 not atomic?

It compiles to a load, an add and a store. Another thread can run between any two of them and its update is then overwritten.

Worked: x starts at 0. Two threads each run x = x + 1 once with no lock. What final values are possible?

1 or 2. If one thread finishes all three steps before the other loads, the result is 2. If both load 0 before either stores, both store 1.

Worked: same setup, but each thread runs x = x + 1 twice. What final values are possible?

2, 3 or 4. The minimum is 2, not 1: thread A loads 0, thread B completes its first increment, A stores 1, B loads 1 for its second increment, A completes its second increment, B stores 2.

What initial value makes a semaphore a mutex, and who signals it?

1. The thread that waited on it signals it when leaving the critical section.

Worked: thread A prints "A", thread B prints "B". Force the output to be "AB" with one semaphore.

Use s = 0. A does print A; signal(s). B does wait(s); print B. If B runs first it blocks until A has printed.

Worked: at most 3 threads may use a device at once. Which semaphore and which calls?

s = 3. Each thread does wait(s), uses the device, then signal(s). A fourth arrival finds 0 and blocks.

In your Lab 7 semsignal, why is the count not incremented when a waiter is found?

The permit goes straight to the waiter. Incrementing as well would create two permits from one signal.

Worked: bounded buffer with N = 4. The producer has run 6 times and the consumer 3 times, none blocked now. What are spaces and items?

The buffer holds 6 − 3 = 3 values, so items = 3 and spaces = 1. They always sum to N.

What goes wrong if the producer does wait(mutex) before wait(spaces)?

With a full buffer the producer blocks on spaces while holding mutex. The consumer blocks on mutex and can never free a slot. Deadlock.

Worked: T1 does wait(A); wait(B). T2 does wait(B); wait(A). Both semaphores start at 1. Give an interleaving that deadlocks.

T1 wait(A) succeeds, T2 wait(B) succeeds, T1 wait(B) blocks, T2 wait(A) blocks. Each holds what the other needs.

Which deadlock condition does lock ordering remove?

Circular wait. If everyone acquires in increasing order, a thread holding lock k only waits for higher-numbered locks, so no cycle can form.

Can a race condition happen on a single core?

Yes. A timer interrupt can switch threads between the load and the store. Interleaving needs preemption, not multiple processors.

2Lecture 21 · Cache coherence

Without a protocol, a core could keep reading its own stale copy of a line after another core has written it. Coherence protocols make the caches behave as if there were one copy.

In a snooping design all caches watch a shared bus. A cache announces what it is about to do with a line, and the others react by giving up or downgrading their copies. Each cache keeps a small state per line. The simplest protocol has three.

StateThis cacheOther cachesMemoryLab 6 name
M ModifiedOnly copy, may read and writeNoneStaleDirty
S SharedRead-only copyMay also hold copiesUp to dateClean
I InvalidNo usable copyAnythingUnknownNotValid

Every MSI transition in one table

Rows are the line's current state in one cache. The first two columns are what its own processor does. The last two are what it sees another cache announce on the bus.

StateOwn readOwn writeSees another read (BusRd)Sees another write (BusRdX)
IMiss. Send BusRd → SMiss. Send BusRdX → Mstay Istay I
SHit, stay SSend upgrade (invalidate others) → Mstay S→ I
MHit, stay MHit, stay MSupply the data, write memory → SSupply the data → I

The pattern to remember: reading needs at least S, writing needs M, and getting M means everyone else goes to I. Every cell follows from that.

Drive the protocol yourself

Tool

MSI and MESI stepper: pick the next access

Both caches start Invalid. Pick an access.

MESI: one more state to make private data free

In MSI a core that reads a line and then writes it sends two bus messages, even when no other core has the line. MESI adds Exclusive: the only copy, still clean. A read miss that finds no other holder enters E, and a later write moves E to M silently. Most data is private to one thread, so this removes most upgrade messages. Turn on MESI in the tool and compare the message count for "core 0 reads, core 0 writes".

StateCopies elsewhere?Matches memory?Write without bus message?
MNoNoYes
ENoYesYes, becomes M
SPossiblyYesNo, must invalidate others
In/an/aNo, must fetch

False sharing

Coherence works on whole lines, not variables. Two threads writing different variables that sit in the same line fight over it exactly as if they shared one variable.

The program is correct. It is only slow, because every write misses. The fix is layout: put data written by different threads in different lines, for example by padding each thread's counter to the line size. The general lesson is that performance depends on the unit the hardware manages, and here that unit is the cache line.

Recall

State the invariant that every coherence protocol maintains.

For each line, either one cache has it writable and no one else has it, or any number have it read-only and all those copies are equal.

Worked: both caches Invalid. Core 0 reads, core 1 reads, core 0 writes. Give the MSI states after each step.

(S, I), then (S, S), then (M, I). The write is an upgrade that invalidates core 1.

Worked: continue from (M, I). Core 1 reads. What happens and what are the states?

Core 1 sends BusRd. Core 0 supplies the data and memory is updated. States become (S, S).

Worked: from (S, S), core 1 writes and then core 0 writes. How many invalidations, and what is the final state?

Two. Core 1's upgrade invalidates core 0, giving (I, M). Core 0's write is a miss with BusRdX, core 1 supplies the data and is invalidated, giving (M, I).

Why must a cache in M respond when it sees another cache's read?

It holds the only correct copy. Memory is stale, so if it stayed silent the reader would get an old value.

What does the E state save, and when?

The upgrade message on a read-then-write of a line no other cache holds. E to M is silent.

Worked: under MESI, both Invalid. Core 0 reads, core 0 writes, core 1 reads. States after each step?

(E, I), then (M, I) with no bus message, then (S, S) after core 0 supplies the data.

How do NotValid, Clean and Dirty from Lab 6 relate to MSI?

They are I, S and M for a system with one cache. Dirty means memory is stale and the line must be written back before it is dropped, which is also what M means.

Two threads increment two different counters and the program gets slower with two cores than with one. What is the likely cause?

False sharing. The counters share a cache line, so each write invalidates the other core's copy and every access misses.

Does false sharing give wrong results?

No. Each variable has one writer, and the protocol keeps the line consistent. Only performance suffers.

Does cache coherence make x = x + 1 atomic across cores?

No. Coherence guarantees each individual load and store sees a consistent value. The three-step sequence can still interleave, so a lock is still needed.

3Lecture 22 · Parallel processing

A single core stopped getting much faster, so performance now comes from doing several things at once. How much it helps depends on how much of the work can actually be done at once.

QuantityDefinitionReading
Speed-upS(n) = T(1) / T(n)How many times faster with n cores
Amdahl's lawS(n) = 1 / ((1 − p) + p / n)p is the fraction of one-core time that parallelises
LimitS(∞) = 1 / (1 − p)Set only by the serial fraction
EfficiencyE(n) = S(n) / nFraction of the added hardware that turned into speed
Chart

Speed-up against cores for four parallel fractions

Going from 90% to 99% parallel matters far more than going from 16 to 64 cores at 90%. Reducing the serial part is usually the better investment.

Two kinds of parallelism

Data-level: one instruction, many elements (SIMD)

One control flow. A wide register holds several values and one instruction operates on all of them. Works when the same operation applies to every element independently.

Thread-level: several instruction streams (multicore)
t0t1t2t3
core 0A1A2A3A4
core 1B1B2B3B4

Independent control flows, each with its own program counter and registers, sharing memory. Works for unrelated tasks too, and brings every problem from Lectures 20 and 21.

Why scaling stops before Amdahl's limit

CostWhere it comes fromLecture
Serial sectionsSetup, input and output, combining results22
Lock contentionThreads waiting to enter critical sections. A lock makes that code serial again20
Coherence trafficInvalidations and line transfers on shared or falsely shared data21
Shared resourcesOne memory bus and one last-level cache serve all cores12, 21
Uneven workOne thread gets the large piece and the others wait for it22

All five behave like an increase in the serial fraction, and some of them grow with the number of cores. That is why measured speed-up curves can bend downward at high core counts, which the formula alone never predicts.

Recall

Worked: 90% of a program parallelises. What is the speed-up on 10 cores, and the limit?

1 / (0.1 + 0.9 / 10) = 1 / 0.19 = 5.26. The limit is 1 / 0.1 = 10.

Worked: what is the efficiency in the previous question?

5.26 / 10 = 53%. About half of the added hardware is wasted waiting on the serial part.

Worked: you need a speed-up of 8 on 16 cores. What parallel fraction is required?

(1 − p) + p / 16 = 1 / 8. So 1 − 0.9375 p = 0.125 and p = 0.933. About 93% must be parallel.

Worked: a program spends 20 s in serial code and 80 s in parallel code on one core. How long on 4 cores?

20 + 80 / 4 = 40 s. Speed-up is 100 / 40 = 2.5.

Worked: half the program parallelises perfectly. Is 2× achievable?

Only as a limit. The bound is 1 / (1 − 0.5) = 2 with infinite cores. With 8 cores it is 1 / (0.5 + 0.0625) = 1.78.

What is the difference between data-level and thread-level parallelism?

Data-level applies one operation to many data elements under a single control flow. Thread-level runs several independent instruction streams at once.

Why does a critical section reduce parallel speed-up?

Only one thread can run it at a time, so it counts toward the serial fraction no matter how many cores exist.

Adding cores made a program slower. Name two possible reasons.

Coherence traffic from shared or falsely shared lines, and lock contention. Both grow as more threads touch the same data.

Why does SIMD need the loop iterations to be independent?

All elements are computed in the same instruction. If iteration i needed the result of iteration i − 1, that result would not exist yet.

4Exam checklist

Know this cold

Related pages: Lab 7 for the kernel that implements these semaphores, Lab 6 for the single-core cache, Lectures 16 to 19 for processes and interrupts.