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.
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.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.
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.
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.
One permit, so one thread inside. The same thread waits and signals.
N identical resources, such as free buffer slots. The fourth requester blocks until one comes back.
No permit exists until A finishes, so B cannot start early. Different threads wait and signal.
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.
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.
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.
Run time on n cores, as a fraction of the one-core time
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.
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.
| Term | Meaning |
|---|---|
| Thread | An independent sequence of execution with its own registers and stack. Threads of one process share memory. |
| Race condition | The outcome depends on the relative timing of threads. |
| Critical section | A region that reads and writes shared state and must run without overlap. |
| Mutual exclusion | At most one thread is in the critical section at any time. |
| Atomic | Appears to happen all at once. No other thread can see a half-finished state. |
| Operation | Definition | Your 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 |
kputc in the same file, which polls the display's ready bit in a loop.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.
spaces + items = N. The semaphores are the buffer's occupancy, kept in a form threads can block on.mutex first and then blocking on spaces would hold the lock while asleep, and the consumer could never get in to free a slot.mutex can be dropped. With several of either it is required.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) | Meaning | How to break it |
|---|---|---|
| Mutual exclusion | The resource cannot be shared | Often impossible to remove |
| Hold and wait | A thread keeps what it has while asking for more | Acquire everything at once, or release and retry |
| No preemption | A resource cannot be taken away | Timeouts or rollback |
| Circular wait | A cycle exists in the who-waits-for-whom graph | Give locks a global order and always acquire in that order |
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
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.
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.
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.
1. The thread that waited on it signals it when leaving the critical section.
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.
s = 3. Each thread does wait(s), uses the device, then signal(s). A fourth arrival finds 0 and blocks.
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.
spaces and items?The buffer holds 6 − 3 = 3 values, so items = 3 and spaces = 1. They always sum to N.
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.
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.
Circular wait. If everyone acquires in increasing order, a thread holding lock k only waits for higher-numbered locks, so no cycle can form.
Yes. A timer interrupt can switch threads between the load and the store. Interleaving needs preemption, not multiple processors.
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.
| State | This cache | Other caches | Memory | Lab 6 name |
|---|---|---|---|---|
| M Modified | Only copy, may read and write | None | Stale | Dirty |
| S Shared | Read-only copy | May also hold copies | Up to date | Clean |
| I Invalid | No usable copy | Anything | Unknown | NotValid |
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.
| State | Own read | Own write | Sees another read (BusRd) | Sees another write (BusRdX) |
|---|---|---|---|---|
| I | Miss. Send BusRd → S | Miss. Send BusRdX → M | stay I | stay I |
| S | Hit, stay S | Send upgrade (invalidate others) → M | stay S | → I |
| M | Hit, stay M | Hit, stay M | Supply the data, write memory → S | Supply 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.
Both caches start Invalid. Pick an access.
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".
| State | Copies elsewhere? | Matches memory? | Write without bus message? |
|---|---|---|---|
| M | No | No | Yes |
| E | No | Yes | Yes, becomes M |
| S | Possibly | Yes | No, must invalidate others |
| I | n/a | n/a | No, must fetch |
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
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.
(S, I), then (S, S), then (M, I). The write is an upgrade that invalidates core 1.
Core 1 sends BusRd. Core 0 supplies the data and memory is updated. States become (S, S).
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).
It holds the only correct copy. Memory is stale, so if it stayed silent the reader would get an old value.
The upgrade message on a read-then-write of a line no other cache holds. E to M is silent.
(E, I), then (M, I) with no bus message, then (S, S) after core 0 supplies the data.
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.
False sharing. The counters share a cache line, so each write invalidates the other core's copy and every access misses.
No. Each variable has one writer, and the protocol keeps the line consistent. Only performance suffers.
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.
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.
| Quantity | Definition | Reading |
|---|---|---|
| Speed-up | S(n) = T(1) / T(n) | How many times faster with n cores |
| Amdahl's law | S(n) = 1 / ((1 − p) + p / n) | p is the fraction of one-core time that parallelises |
| Limit | S(∞) = 1 / (1 − p) | Set only by the serial fraction |
| Efficiency | E(n) = S(n) / n | Fraction of the added hardware that turned into speed |
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.
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.
| t0 | t1 | t2 | t3 | |
|---|---|---|---|---|
| core 0 | A1 | A2 | A3 | A4 |
| core 1 | B1 | B2 | B3 | B4 |
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.
| Cost | Where it comes from | Lecture |
|---|---|---|
| Serial sections | Setup, input and output, combining results | 22 |
| Lock contention | Threads waiting to enter critical sections. A lock makes that code serial again | 20 |
| Coherence traffic | Invalidations and line transfers on shared or falsely shared data | 21 |
| Shared resources | One memory bus and one last-level cache serve all cores | 12, 21 |
| Uneven work | One thread gets the large piece and the others wait for it | 22 |
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
1 / (0.1 + 0.9 / 10) = 1 / 0.19 = 5.26. The limit is 1 / 0.1 = 10.
5.26 / 10 = 53%. About half of the added hardware is wasted waiting on the serial part.
(1 − p) + p / 16 = 1 / 8. So 1 − 0.9375 p = 0.125 and p = 0.933. About 93% must be parallel.
20 + 80 / 4 = 40 s. Speed-up is 100 / 40 = 2.5.
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.
Data-level applies one operation to many data elements under a single control flow. Thread-level runs several independent instruction streams at once.
Only one thread can run it at a time, so it counts toward the serial fraction no matter how many cores exist.
Coherence traffic from shared or falsely shared lines, and lock contention. Both grow as more threads touch the same data.
All elements are computed in the same instruction. If iteration i needed the result of iteration i − 1, that result would not exist yet.
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.