Lecture 17 · Transactional Memory (Part I)

Parallel Computing · Lecture 17。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: Stanford CS149 Fall 2025, Lecture 17 (Dec 2), slide deck 17_transactionalmem (50 slides). Sources: the public Fall 2025 slides; M. Herlihy, J. E. B. Moss, “Transactional Memory: Architectural Support for Lock-Free Data Structures” (ISCA 1993); J. Larus, R. Rajwar, Transactional Memory (Morgan & Claypool, 2007); T. Harris, J. Larus, R. Rajwar, Transactional Memory, 2nd ed. (2010); L. Hammond et al., “Transactional Memory Coherence and Consistency” (ISCA 2004, the “TCC” of slide 27); L. Dalessandro, M. F. Spear, M. L. Scott, “NOrec: Streamlining STM by Abolishing Ownership Records” (PPoPP 2010). Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro; clang 21, macOS 27). Apple’s chips have no hardware transactional memory, so the policies are studied in a simulator, and a small software TM runs the real-thread demo. Code: code/lecture17/. Reading time: ~70 minutes for the prose; ~10 more for the demos.


0. How to read this lecture

0.1 Learning goals

Slide 3 lists what you should know after this lecture:

  1. What a transaction (事务) is: atomicity, isolation, serializability.
  2. The difference in semantics between an atomic { } block and lock() / unlock().
  3. The basic design space of TM implementations: the data versioning (数据版本管理) policy, the conflict detection (冲突检测) policy, and the granularity of detection.
  4. The basics of software and hardware implementations. These are mostly Lecture 18, but these notes also build one small software TM.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 15: atomics, memory orders, CAS.
    • Lecture 16: deadlock, fine-grained locking, lock-free structures, ABA.
  • Scope: what transactions promise, why they are attractive, and the two policy choices every implementation makes. Concrete software TM algorithms (TL2 and friends) and hardware TM are Lecture 18.

0.3 Section → code map

SectionIdeaDemo in code/lecture17/
§2–§3composability, failure atomicity, misuse of atomic03_tm_semantics.py (uses tmsim.py)
§3.2transactions on trees and hash maps vs locks02_tm_workloads.py Parts A–B
§4.2eager vs lazy versioning01_tm_policies.py Part A
§4.3pessimistic vs optimistic detection01_tm_policies.py Parts B–D, 02_tm_workloads.py Part C
§5a real STM on real threads04_bank_stm (uses norec.h)

Run them all with cd code/lecture17 && make run (~2 seconds).

0.4 Notation

  • atomic { … }: a transaction. Commit (提交): the transaction’s writes take effect. Abort (中止): they are discarded, and the transaction usually retries (重试).
  • Read set / write set (读集 / 写集): the addresses a transaction has read / written so far.
  • Conflict: two concurrent transactions access the same address, and at least one writes it.

1. Raising the level of abstraction for synchronization (slides 2–4)

The last three lectures climbed a ladder (slide 2):

  • machine-level atomic operations: test-and-set, fetch-and-op, compare-and-swap, LL/SC;
  • built from them: locks, barriers and lock-free data structures.

Each step made correct programs possible, and each made it easy to write incorrect ones: atomicity violations, deadlock, ABA, use-after-free.

Locks force a trade-off (slide 4, “between a lock and a hard place”) between concurrency, which is performance, and the chance of races and deadlock, which is correctness:

  • Coarse-grained locks, such as one lock for the whole data structure: low concurrency, high chance of being correct.
  • Fine-grained locks, such as hand-over-hand locking: high concurrency, lower chance of being correct. Lecture 16’s measurements add that they are not always faster either.

Is there a better abstraction? This lecture’s answer is transactional memory (事务内存).


2. Programming with transactions (slides 5–9)

2.1 From locks to atomic (slides 5–7)

A deposit is a read-modify-write that must be atomic with respect to other operations on the same account (slide 5). With locks:

void deposit(Acct account, int amount) {
    lock(account.lock);
    int tmp = bank.get(account);
    tmp += amount;
    bank.put(account, tmp);
    unlock(account.lock);
}

With a transaction (slide 6):

void deposit(Acct account, int amount) {
    atomic {
        int tmp = bank.get(account);
        tmp += amount;
        bank.put(account, tmp);
    }
}

The difference is more than syntax. atomic is declarative (声明式): the programmer states what must hold (this code runs atomically), not how to achieve it. There is no lock to choose, name or order. The system implements the synchronization. It could use locks (§5 shows one way), but the implementations of this lecture use optimistic concurrency (乐观并发): run transactions in parallel, and serialize them only when there is a true read-write or write-write conflict. This is the same declarative-vs-imperative distinction as Lecture 8 (slide 7): “perform this set of operations atomically”, like “execute these 1,000 independent tasks”, leaves the strategy to the system.

2.2 What a transaction promises (slides 8–9)

A memory transaction is an atomic and isolated sequence of memory accesses, inspired by database transactions. It has three properties:

  • Atomicity (原子性), all or nothing. At commit, all of the transaction’s writes take effect at once. On abort, none of them appear to have happened, as if the transaction never ran.
  • Isolation (隔离性). No other processor can observe the transaction’s writes before it commits.
  • Serializability (可串行化). Transactions appear to commit in a single serial order. The semantics do not say which order.

Slide 9 makes the link to Lecture 14. Coherence gives a single address one agreed history; a transaction gives a whole set of reads and writes one agreed moment. Its reads (say X, Y, Z) and writes (say A, X) are observed by other processors all together or not at all. What about the consistency model for TM (slide 9’s question)? Transactions behave as if each one executed in a single global order, a kind of sequential consistency at transaction granularity. That ordering holds between transactions. How transactional code interacts with non-transactional accesses to the same data (“strong” vs “weak” isolation) is one of the subtle points real TM systems must define.


3. Why transactions? (slides 10–37)

3.1 A hash map (slides 11–15)

Java’s HashMap (slide 11) is a table of buckets, each holding a linked list. It is not thread-safe, and it has no lock overhead when synchronization is not needed. The two lock-based ways to make it thread-safe are the usual two:

  • A synchronized wrapper (slide 12; Java 1.4’s Collections.synchronizedMap): one lock guards every access. Easy, thread-safe, and it limits concurrency.
  • A lock per bucket (slide 13): thread-safe and concurrent, at the cost of lock overhead on every access even when there is no contention, and of having to get it right.

Slide 14 shows fine-grained locks winning over coarse ones as processors are added, for a balanced tree and a hash table. The transactional version (slide 15) simply puts each operation in an atomic block: thread-safe and easy. How well it performs depends on the workload and the TM implementation.

3.2 Updating a tree (slides 16–27)

Two threads want to modify leaves 3 and 4 of a tree whose path from the root is 1 → 2 → {3, 4} (slide 16):

  • With hand-over-hand locking (slides 17–22), both threads lock nodes 1 and 2 on their way down, so the locks on the shared ancestors delay the second update even though the two updates touch different leaves (slide 22).
  • As transactions (slides 23–25), A reads {1, 2, 3} and writes {3}, and B reads {1, 2, 4} and writes {4}. There are no read-write or write-write conflicts, because no transaction writes data the other accesses. Both run fully in parallel.
  • If both modify node 3 (slide 26), they conflict and must be serialized.

Demo 02 runs this in parallel time, with one memory operation per thread per step:

two updatesTM (any policy)one global lockhand-over-hand locks
different leaves8 steps, no aborts1416
the same leaf14–15 steps, 1 abort1418

Slide 27 shows the hardware TM system TCC (Transactional Coherence and Consistency, Hammond et al., 2004) matching or beating fine-grained locks on a balanced tree and a hash map.

Demo 02 also runs a hash map with 64 buckets: 4 threads, 30 operations each, half of them inserts.

  • Without a shared counter: transactions finished 3.5× faster than one global lock, with a single abort.
  • With a shared counter: every insert also updates a size counter, a very natural thing to add. The speedup fell to 1.8–2.1×, with 11–23 aborts. One shared variable that every transaction writes turns TM back toward a global lock.

Transactions are only as concurrent as the data they actually touch.

3.3 Atomic regions in a doubly linked list (slide 28)

PushLeft on a doubly linked queue reads the left sentinel and its right neighbour, then updates four pointers. Making it thread-safe with locks means deciding which nodes to lock, in which order. With a transaction, the four pointer updates go in one atomic block, and the system works out what conflicts.

3.4 Failure atomicity (slides 29–30)

A transfer that throws an exception halfway is a correctness hazard with locks (slide 29). The programmer must write undo code for each exception case, track what to undo and how, and accept that partial updates were visible to other threads in the meantime. An unhandled case can leave a lock held and deadlock the system. With a transaction (slide 30) the system handles it. Any exception the programmer does not handle aborts the transaction and undoes its memory updates, and no locks are left held.

Demo 03 debits A by 100 and then throws before crediting B:

  • with locks and no undo code: A = 900, B = 1000, and 100 is gone;
  • as a transaction, under either versioning policy: A = 1000, B = 1000.

Demo 04 does it on real threads with the STM of §5. 4 threads attempted transfers far larger than the balances, so 64,016 transfers threw after their deposit had already been made. The total stayed exactly 64,000, and no account went below zero.

3.5 Composability (slides 31–33)

Transfers built by nesting per-account locks deadlock when two threads transfer in opposite directions (slide 31): thread 0 runs transfer(A, B, 100), thread 1 runs transfer(B, A, 200), and each holds one account’s lock while waiting for the other’s. Avoiding that requires a system-wide policy such as a global lock order, and such policies break modularity: every module must know and obey the order (slide 32).

Transactions compose (slide 33). The caller declares the atomicity it needs:

void transfer(A, B, amount) {
    atomic {
        withdraw(A, amount);       // these may contain atomic blocks of their own;
        deposit(B, amount);        // the outermost transaction defines the boundary
    }
}

The system serializes transfer(A, B, 100) with transfer(B, A, 200), and lets transfer(A, B, 100) and transfer(C, D, 200) run concurrently.

The demos show both halves of that claim.

  • Demo 03:

    • the nested-lock version deadlocks;
    • the transactional version completes 50 transfers each way with the sum conserved;
    • transfers on disjoint accounts have zero aborts.
  • Demo 04, on real threads, with an auditor thread summing all 64 accounts while 4 threads transfer:

    transfer built fromwrong audits
    withdraw() and deposit(), each correctly locked3,951 of 4,166 (~95%: money “in flight”)
    both accounts locked in address order; the auditor locks all 64 accounts0 of 27,870
    atomically { deposit(); withdraw(); }; the auditor is atomically { sum all }0 of 2,487

    The lock-based fix works, but it required a global lock order, and an auditor that knows to lock every account. The transactional version required neither.

3.6 The promise, and what atomic is not (slides 34–37)

Slide 34 lists what transactional memory promises:

  • easy-to-use synchronization, “as easy as coarse-grain locks”;
  • performance often comparable to fine-grained locks: automatic read-read concurrency, and portability across machine sizes;
  • failure atomicity and recovery;
  • composability.

But atomic { } ≠ lock(); … unlock(); (slide 35):

  • atomic is a high-level declaration of atomicity, and it does not specify the implementation.
  • A lock is a low-level blocking primitive, and on its own it provides neither atomicity nor isolation.
  • Locks can implement atomic blocks, and they also have uses beyond atomicity, so not every lock can be replaced by an atomic region.

Slide 36’s example shows the difference:

// Thread 1                          // Thread 2
synchronized(lock1) {                synchronized(lock2) {
    flagA = true;                        flagB = true;
    while (flagB == 0);                  while (flagA == 0);
}                                    }

With two different locks this works: each thread’s write is visible at once, and both threads get through. Replace synchronized with atomic, and isolation means neither transaction can see the other’s flag before it commits. Neither commits before it sees the other’s flag. Demo 03 shows both policies failing: under optimistic detection, both spin forever on stale flags; under pessimistic detection, both stall on each other’s uncommitted write. Code that waits inside a transaction for another thread’s write is not a transaction.

Slide 37 shows a programmer error that atomic does not fix:

// Thread 1                          // Thread 2
atomic { ptr = A; }                  atomic { ptr = NULL; }
atomic { B = ptr->field; }

Each block is atomic, but the logical operation was split in two, and thread 2’s transaction can run in between. Demo 03 produces exactly that: B = NULL->field, a crash. One atomic block around both statements gives B = 42. Atomic blocks eliminate many data races, but not atomicity violations.


4. Implementing transactional memory (slides 38–50)

4.1 Two questions (slides 39–40)

An implementation must provide atomicity and isolation while keeping as much concurrency as possible. Two design questions follow:

  1. Data versioning. Where do uncommitted (new) and previously committed (old) values live while transactions run?
  2. Conflict detection. How, and when, does the system find out that two concurrent transactions conflict?

A third question, the granularity of detection (word, cache line, object), is Lecture 18’s.

4.2 Data versioning: eager vs. lazy (slides 41–44)

Eager versioning (急切版本管理) uses an undo log (slide 42). The transaction updates memory in place immediately, and records the old value in an undo log (撤销日志):

  • commit: discard the log;
  • abort: copy the old values back.

Lazy versioning (惰性版本管理) uses a write buffer (slide 43). Writes go into a per-transaction write buffer (写缓冲), and memory is untouched:

  • commit: copy the buffer to memory;
  • abort: discard the buffer.

Demo 01, Part A, starts with x = 10 and runs a transaction that writes x ← 15:

eager, commit:  t=1  memory x = 15   undo log {'x': 10}   ...   t=3  memory x = 15   (done)
eager, abort:   t=1  memory x = 15   undo log {'x': 10}   ...   t=3  memory x = 10   (rolled back)
lazy,  commit:  t=1  memory x = 10   write buffer {'x': 15}  ...  t=3  memory x = 15
lazy,  abort:   t=1  memory x = 10   write buffer {'x': 15}  ...       memory x = 10   (buffer dropped)

The trade-offs (slide 44):

eager (undo log)lazy (write buffer)
philosophywrite to memory immediately, hoping the transaction won’t abortonly write to memory when you have to
per-store costlog the old valuebuffer the new value, and look reads up in the buffer
commitfast: data already in memoryslow: copy the buffer
abortslow: restore from the logfast: drop the buffer
fault tolerancea crash mid-transaction leaves new values in memoryno issue

4.3 Conflict detection: pessimistic vs. optimistic (slides 45–50)

Two concurrent, pending transactions can conflict in two ways (slide 45):

  • read-write: A reads X, which B has written but not committed;
  • write-write: both write X.

To find conflicts, the system tracks each transaction’s read set and write set.

Pessimistic detection (悲观检测), also called “eager”, checks for conflicts on every load and store (slide 46). Its philosophy: “if I’m going to have to roll back, might as well do it now”. When a conflict is found, a contention manager (争用管理器) decides whether to stall one transaction or abort one. Slide 47’s diagrams assume an aggressive manager: a writer wins and the other transaction aborts, while a reader stalls behind an uncommitted writer. Demo 01, Part B, runs the four cases:

casewhat happensoutcome
1. no conflict—both commit
2. T1 reads A, which T0 has writtenT1 stalls 3 steps until T0 commits, then readsearly detect, no wasted work
3. T1 writes A, which T0 has readT0 aborts immediately (writer wins), restarts, commits laterabort, 4 steps wasted
4. T0 and T1 both write A, then work, retrying at onceeach write aborts the other, foreverno progress: 15 aborts in 40 steps

Case 4 is livelock (Lecture 16). Slide 47 asks how to avoid it, and demo 01 shows two answers:

  • back-off that differs between the threads: both commit, after 1 abort;
  • a contention manager in which the older transaction wins: the younger one aborts itself and retries until the older commits.

Optimistic detection (乐观检测), also called “lazy” or “commit-time”, detects conflicts only when a transaction tries to commit (slide 48): “hope for the best, sort out conflicts at commit”. The committing transaction has priority, and transactions that conflict with it abort. Demo 01, Part C, runs slide 49’s four cases:

casewhat happensoutcome
1. no conflict—both commit
2. T1 commits a write of A, which T0 has readT0 aborts at T1’s commit and restartsabort, 5 steps wasted
3. T0 commits its read of A before T1 commits its writeno conflict at T0’s commitboth succeed, serial order T0, T1
4. both read and write Athe first to commit wins; the other restartsforward progress, 1 abort

The trade-offs (slide 50):

pessimistic (“eager”) detectionoptimistic (“lazy”, “commit”) detection
+ detects conflicts early: less work to undo, and some aborts become stalls+ forward progress guaranteed: the committer always wins
− no forward-progress guarantee; more aborts in some cases+ communication and detection in bulk, at commit
− fine-grained communication: a check on every load and store, on the critical path− detects conflicts late: losers waste their work; fairness problems remain

4.4 Which combinations make sense?

Combining the two choices gives four designs, and only three are sound:

  • eager versioning + pessimistic detection, as in LogTM;
  • lazy versioning + pessimistic detection;
  • lazy versioning + optimistic detection, as in TCC and most STMs.

Eager versioning puts uncommitted values in memory, so with optimistic detection, nothing stops another transaction from reading them before the writer commits or aborts. Demo 01, Part D, shows it:

  • T0 writes A = 15 in place, then fails;
  • T1 meanwhile reads A and commits B = A + 1 = 16;
  • T0’s abort restores A = 10, and memory is left with A = 10, B = 16: B was computed from a value that never existed.

That violates isolation, unless every reader is aborted along with the writer (“cascading aborts”).

How do the three sound designs compare as contention grows? Demo 02, Part C, uses random transactions: 4 threads × 25 transactions, each reading 4 of K addresses and writing 2. Time is in steps, until all transactions have committed:

policyK = 256K = 32K = 8K = 2
one global lock100010001000800
eager + pessimistic320 (4 aborts)489 (33)863 (56)725 (54)
lazy + pessimistic351 (5)511 (33)920 (68)826 (56)
lazy + optimistic345 (4)565 (27)925 (57)850 (53)

With little contention every policy is close to the ideal of 4 parallel threads, about 250 steps. As contention grows, the advantage over one lock shrinks. At K = 8 and below, transactions are barely faster than a lock and waste hundreds of steps in aborted attempts. Pessimistic detection converts some conflicts into stalls and found conflicts earlier. Optimistic detection had fewer aborts but more wasted work per abort, because its conflicts are discovered late.


5. A real software TM in about 120 lines of code

Apple’s chips have no hardware TM, and standard C++ has no atomic { } block. A Transactional Memory Technical Specification (2015) and GCC’s -fgnu-tm exist, but neither is part of the standard or supported by Apple clang. To run transactions on real threads, norec.h implements a small but complete STM, after NOrec (Dalessandro, Spear and Scott, 2010):

stm::Word T[64];                                   // transactional words
void transfer_tx(int from, int to, long amt) {
    stm::atomically([&] {
        deposit_tx(to, amt);                       // themselves atomically { ... }: flattened
        withdraw_tx(from, amt);                    // may throw InsufficientFunds -> abort
    });
}

It maps one-to-one onto §4’s choices:

  • Lazy versioning: write appends to a per-transaction write buffer; memory is untouched until commit.
  • Optimistic detection, by value: read logs (address, value). Whenever a global sequence number shows that some transaction committed in the meantime, the reader validates: it re-reads everything it has read and aborts if any value changed. So a transaction never sees an inconsistent snapshot, a property called opacity.
  • Commit: a read-only transaction just finishes. A writer increments the global sequence number to an odd value (the commit lock), writes its buffer to memory, and increments it to even again.
  • Composition and failure atomicity: a nested atomically joins the outer transaction. A user exception discards the buffer and propagates.

Demo 04’s results are in §3.4 and §3.5: every audit exact, failed transfers leaving no trace. And the cost (transfers per microsecond):

1 thread248
one global lock97–13149–7520–2613–19
per-account locks, address order52–6715–3013–167.7–8.8
transactions (NOrec STM)41–4613–244.4–5.02.6

Read it honestly:

  • None of the three gets faster with more threads. A transfer is two tiny updates; the threads mostly fight over the same 64 cache lines, and the lock or the commit counter.
  • The STM pays for its bookkeeping: at one thread it is 1.1–1.6× slower than per-account locks and 2–3× slower than one global lock (logging, validation). At 8 threads it is 3× slower than per-account locks and 5–7× slower than the global lock, because its shared commit counter serializes all writers. A first version allocated its logs anew for every transaction and was 5–10× slower even on one thread. Malloc in the transaction path was the real cost (found while writing Lecture 18); now each thread reuses one descriptor.

What transactions bought here is correctness and composability, not speed. Lecture 18 asks where STM time goes, and how designs with per-location metadata (TL2) and hardware support change the picture.


Summary

  • A transaction is atomic (all or nothing), isolated (no partial results visible) and serializable (some single order). atomic { } declares what must be atomic; the system decides how.
  • Transactions run in parallel unless they conflict. Disjoint tree leaves or hash buckets proceed concurrently, where locks on shared ancestors serialize. A shared counter updated by every transaction serializes them again.
  • Transactions give failure atomicity (an exception aborts and undoes) and composability (nesting joins the outer transaction; no lock order). Demo 04 on real threads: separately locked withdraw + deposit failed ~95% of audits; transactions failed none.
  • atomic is not a lock. Waiting inside a transaction for another thread’s write hangs. Splitting one logical operation into two atomic blocks is still an atomicity bug.
  • Versioning: eager (in place + undo log: fast commit, slow abort) or lazy (write buffer: fast abort, slow commit). Detection: pessimistic (at each access: early, stalls, possible livelock) or optimistic (at commit: committer wins, forward progress, late discovery). Three combinations are sound; eager + optimistic exposes uncommitted data.
  • A complete STM fits in ~120 lines (NOrec: write buffer + value validation + a global commit counter). It was correct and composable, and 1.1–7× slower than locks on tiny transfers.

Common pitfalls

  • Treating atomic as a lock. Spinning on a flag, or waiting on a condition another thread sets, inside a transaction hangs or livelocks.
  • Splitting a logical operation into several atomic blocks. Each block is atomic; the sequence is not. Make the atomic block as large as the invariant it protects.
  • Doing irrevocable things inside a transaction: I/O, printing, system calls, launching missiles. A transaction may run several times and abort; its side effects outside memory cannot be undone.
  • A shared counter in every transaction, such as a size, a sequence number or statistics. It makes all transactions conflict; keep such counters per thread, or update them outside.
  • Expecting speed from TM on tiny critical sections. Logging and validation cost more than a short lock hold. Transactions pay off on larger operations with real disjointness.
  • Mixing transactional and non-transactional access to the same data. Under weak isolation, a plain write can break a transaction’s view. Access shared data either always inside transactions, or never.
  • Pessimistic TM without a contention manager. Two writers can abort each other forever. Use back-off or an age-based policy.

Exercises

  1. Serializability. Transaction T1 does x = 1; y = 1; and transaction T2 does r1 = x; r2 = y; (initially 0). Which outcomes (r1, r2) can a TM system produce? Compare with the same code as plain threads on a weakly ordered machine (Lecture 15).

    AnswerAs transactions: only (0, 0) (T2 serialized before T1) or (1, 1) (after). (1, 0) and (0, 1) would show half of T1's writes, which violates atomicity and isolation. As plain threads on a weak machine, all four outcomes are possible, including (1, 0): this is the MP test.
  2. Versioning costs. A transaction writes 20 values and aborts with probability p. Each write costs 1, plus 1 more for logging under eager versioning or buffering under lazy. An eager commit costs 1 and an eager abort 20; a lazy commit costs 20 and a lazy abort 1. For which p is eager cheaper per attempt?

    AnswerThe write costs are the same under both (20 + 20), so compare commit and abort: eager costs (1 − p)·1 + p·20 = 1 + 19p, and lazy costs (1 − p)·20 + p·1 = 20 − 19p. Eager is cheaper when 1 + 19p < 20 − 19p, i.e. p < 0.5. Eager wins when aborts are rare, which is the common case TM is designed for. Lazy wins when conflicts are frequent.
  3. Early or late? T0 runs rd A; rd B; work 10; wr C. T1 starts 2 steps later and runs wr A; commit. How much of T0’s work is wasted under pessimistic detection with writer wins, and under optimistic detection?

    AnswerPessimistic: T1's write of A at step 2 aborts T0 immediately, so only T0's first 2 steps are wasted, and T0 restarts. Optimistic: T1 commits at about step 3, and since A is in T0's read set, T0 is aborted then. Only ~3 steps are wasted, because the committer's check happens early in this case. If instead T1 did a long computation before committing, T0 might commit first (case 3 of slide 49) and nothing would be wasted. Or, if T1 committed just before T0's commit, T0 would have done all its work for nothing: optimistic detection's worst case.
  4. Livelock. Explain why slide 47’s case 4 can make no progress under a “writer wins” contention manager, and why it cannot happen under optimistic detection.

    AnswerPessimistic: T0 writes A, then T1 writes A and aborts T0 (writer wins). T0 restarts and writes A, aborting T1, and so on. Each abort happens before the victim reaches its commit, so neither ever commits. Optimistic: aborts happen only at someone's *commit*, and a transaction that reaches its commit point always succeeds, because it is the committer. So whenever an abort occurs, some transaction has just committed: system-wide progress.
  5. The fourth combination. Explain, with a two-transaction example, why eager versioning cannot be combined with optimistic conflict detection without extra machinery.

    AnswerT0 writes A = 15 in place; the old value 10 is in its log. T1 reads A, gets 15, writes B = 16, and commits, because optimistic detection checks only at commit, and T0 has not committed yet, so T1's commit finds no conflict. Then T0 aborts and restores A = 10. Memory now holds A = 10, B = 16, derived from a value that was never committed. To fix it, a reader of uncommitted data would have to be tracked and aborted with the writer (cascading aborts), or reads of in-place uncommitted data detected at access time, which is pessimistic detection.
  6. Composability with locks. Make transfer(A, B) deadlock-free and atomic using per-account locks. What must every other piece of code in the program know? What does atomic require instead?

    AnswerLock both accounts in a global order (for example, by account id or address), make the changes, then unlock. Every function that ever holds more than one account lock must use the same order, including future code written by others, and any code that needs a consistent view of many accounts (the auditor) must lock all of them in that order. With `atomic`, transfer simply wraps withdraw and deposit; no global policy exists, and an auditor is just another transaction.
  7. Slide 36. Why does replacing synchronized(lock1) and synchronized(lock2) with atomic turn a working hand-shake into a hang? Would a TM implemented with a single global lock behave differently?

    AnswerWith two different locks, both threads run their critical sections at the same time and see each other's flag writes immediately. Under atomic, each transaction's write is invisible to the other until it commits (isolation), and each needs to see the other's write before it can finish, so neither commits. A global-lock implementation of atomic would serialize the two blocks: the first one waits forever for a flag that only the second, blocked, block can set. That is a deadlock instead of a livelock, but it hangs all the same. The program's logic, not the TM implementation, is at fault.
  8. NOrec details. In norec.h, why may a read-only transaction commit without touching the global sequence number? And why is it enough to compare values during validation, without version numbers?

    AnswerA read-only transaction's reads were all validated against one snapshot of `seq` (re-validated whenever `seq` moved), so its view was consistent at some moment. It has nothing to write, so it can serialize at that moment and needs no commit lock. Value-based validation is enough because the transaction's behaviour depends only on the values it read. If every value is still the same, the transaction's result is the same as if it ran now, even if the locations changed and changed back (A → B → A). For NOrec that is not an ABA bug: the values, not the history, are what matter.

No assignment uses transactional memory directly. The lecture’s lessons apply to PA2’s thread pool and to any shared data structure:

  • prefer coarse, obviously correct synchronization first;
  • measure;
  • refine only where contention shows up;
  • keep shared counters off the common path.

Further reading

  • The Fall 2025 slides for this lecture.
  • M. Herlihy, J. E. B. Moss, “Transactional Memory: Architectural Support for Lock-Free Data Structures”, ISCA 1993: the paper that started it.
  • T. Harris, J. Larus, R. Rajwar, Transactional Memory, 2nd ed., Morgan & Claypool, 2010: the design space of this lecture, systematically.
  • L. Hammond et al., “Transactional Memory Coherence and Consistency”, ISCA 2004 (TCC, slide 27).
  • K. E. Moore, J. Bobba, M. J. Moravan, M. D. Hill, D. A. Wood, “LogTM: Log-based Transactional Memory”, HPCA 2006: eager versioning in hardware.
  • L. Dalessandro, M. F. Spear, M. L. Scott, “NOrec: Streamlining STM by Abolishing Ownership Records”, PPoPP 2010 (norec.h).
  • C. Blundell, E. C. Lewis, M. M. K. Martin, “Subtleties of Transactional Memory Atomicity Semantics”, IEEE Computer Architecture Letters, 2006: strong vs weak isolation.

Preview of Lecture 18 — Transactional memory (Part II) + course wrap-up

Lecture 18 opens the implementations:

  • Software TM: per-location transaction records, how data is mapped to them, the granularity of conflict detection, an STM algorithm with versioned locks and read-set validation (TL2), and why STM is slow.
  • Hardware TM: read/write bits in cache lines, conflict detection by the coherence protocol, and lazy-optimistic HTM. Also why it works until the read set overflows the cache, and what happened to Intel’s and IBM’s implementations.

The lecture then closes the course with its key themes.


术语表 (Glossary, English → 中文)

English中文
transactional memory (TM)事务内存
transaction / atomic block事务 / 原子块
commit / abort / retry提交 / 中止 / 重试
atomicity / isolation / serializability原子性 / 隔离性 / 可串行化
declarative / imperative声明式 / 命令式
optimistic concurrency乐观并发
read set / write set读集 / 写集
read-write conflict / write-write conflict读写冲突 / 写写冲突
data versioning (eager / lazy)数据版本管理(急切 / 惰性)
undo log撤销日志
write buffer (redo log)写缓冲(重做日志)
conflict detection (pessimistic / optimistic)冲突检测(悲观 / 乐观)
commit-time validation提交时校验
contention manager争用管理器
stall停顿(等待)
wasted work浪费的工作
forward progress前向进展
failure atomicity故障原子性
composability / nesting (flattening)可组合性 / 嵌套(展平)
atomicity violation原子性违背
isolation (strong / weak)隔离(强 / 弱)
dirty read / cascading abort脏读 / 级联中止
software TM (STM) / hardware TM (HTM)软件事务内存 / 硬件事务内存
opacity不透明性(事务始终看到一致快照)
value-based validation基于值的校验
global sequence lock全局序列锁
irrevocable operation不可撤销操作
← 返回课程目录