Lecture 18 · Transactional Memory (Part II) + Course Wrap-Up

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

课程源码 ZIP ↓

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

本篇目录

Maps to: Stanford CS149 Fall 2025, Lecture 18 (Dec 4), slide deck 18_transactionalmem (62 slides). Slides 2–11 review Lecture 17. The rest covers TM implementations in software and hardware, then the course wrap-up. Sources: the public Fall 2025 slides; D. Dice, O. Shalev, N. Shavit, “Transactional Locking II” (DISC 2006); B. Saha et al., “McRT-STM: A High Performance Software Transactional Memory System for a Multi-Core Runtime” (PPoPP 2006, slide 17); L. Dalessandro, M. Spear, M. Scott, “NOrec” (PPoPP 2010); L. Hammond et al., “Transactional Memory Coherence and Consistency” (ISCA 2004); Intel, Intel 64 and IA-32 Architectures Optimization Reference Manual, chapter on Intel TSX. Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro; clang 21, macOS 27). That machine has no hardware TM, so HTM is studied in a cache-level simulator. Code: code/lecture18/. Reading time: ~75 minutes for the prose; ~10 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Place real TM systems in the design space of data versioning × conflict detection (slide 12).
  2. Explain what a software TM (STM, 软件事务内存) does at every transactional load, store and commit:
    • its barriers (屏障函数);
    • the per-thread transaction descriptor (事务描述符);
    • the per-data transaction records (事务记录).
  3. Explain how data is mapped to records, and how the granularity (粒度) of conflict detection trades overhead against false conflicts (伪冲突).
  4. Walk through a timestamp-based STM such as TL2 or McRT, and explain why STMs are slow and how compilers reduce the cost.
  5. Explain how hardware TM (HTM, 硬件事务内存) keeps versions in the cache and detects conflicts with the coherence protocol, and why it aborts when a transaction outgrows the cache.
  6. Summarize the course’s key issues, and where to go next.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 17: transactions, versioning, detection.
    • Lecture 14: caches, MSI, invalidations.
    • Lecture 15: atomics, memory orders.
  • Scope: STM and HTM mechanisms. The last part (§5) reviews the whole course.

0.3 Section → code map

SectionIdeaDemo in code/lecture18/
§2.1–§2.4STM data structures, records, granularity, the TL2 algorithmtl2.h
§2.5–§2.6STM vs locks; why STM is slow; false conflicts01_stm_hashmap
§3HTM: R/W bits, coherence-based detection, capacity, fallback, TCC02_htm.py (uses htm.py)

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


1. The implementation space (slides 2–12)

Slides 2–11 review Lecture 17:

  • a transaction is atomic, isolated and serializable;
  • TM promises easy synchronization, performance close to fine-grained locks, failure atomicity and composability. Slide 3 adds the productivity claim: “90% of the benefit of expert programming with fine-grained locks, with 10% of the development time”;
  • every implementation chooses a data versioning policy and a conflict detection policy.

Slide 12 places real systems in that space:

systemversioningdetection
softwareSun TL2lazyoptimistic (reads and writes)
Microsoft OSTMlazyoptimistic reads, pessimistic writes
Intel McRT STMeageroptimistic reads, pessimistic writes
Intel STMeagerpessimistic
hardwareStanford TCClazyoptimistic
MIT LTM, Intel VTMlazypessimistic
Wisconsin LogTMeagerpessimistic (“easiest with conventional cache coherence”)

“Optimal design remains an open question”, and the answer may differ between hardware, software and hybrid systems. The “optimistic reads, pessimistic writes” rows are worth noticing. Many systems detect read conflicts late, by validating at commit, but write conflicts early, by locking a location at the first write. This is the eager-versioning-friendly compromise: eager versioning needs pessimistic detection for writes (Lecture 17 §4.4), while reads can still be optimistic.


2. Software transactional memory (slides 13–30)

2.1 Barriers: what the compiler inserts (slide 13)

An STM is a library plus compiler support. The compiler rewrites every memory access inside atomic { } into a call into the STM runtime, a barrier:

atomic {                              tmTxnBegin();
  a.x = t1;                           tmWr(&a.x, t1);
  a.y = t2;              becomes      tmWr(&a.y, t2);
  if (a.z == 0) {                     if (tmRd(&a.z) != 0) {
    a.x = 0;                              tmWr(&a.x, 0);
    a.z = t3;                             tmWr(&a.z, t3);
  }                                   }
}                                     tmTxnCommit();

The barriers do the bookkeeping:

  • versioning;
  • read-set and write-set tracking;
  • commit;

using locks, timestamps and data copying. A function called both inside and outside transactions needs two versions, one with barriers and one without. This is called function cloning, and the alternative is dynamic translation.

2.2 Runtime data structures (slide 14)

  • Transaction descriptor, one per thread. It holds the read set, the write set, and the undo log or write buffer, and is used for conflict detection, commit and abort.
  • Transaction record, one per piece of data. A pointer-sized word that guards shared data and tracks its transactional state:
    • shared: readable by many, recorded as a version number or a count of readers;
    • exclusive: owned by one writer, recorded as a lock pointing to the owner.

Slide 14 remarks: “BTW: same way that HW cache coherence works”. A transaction record is a software coherence state, kept per data item.

2.3 Mapping data to records, and granularity (slides 15–16)

Every data item needs an associated record (slide 15). Two common mappings:

  • Embed the record in each object. This is natural in Java or C#, where objects already have headers.
  • Hash the address into a global table of records. This works for C/C++ at word or cache-line granularity, or with a hash of (object, field index).

The trade-off is the granularity of conflict detection (slide 16):

granularity+−
objectcheap mapping; optimization opportunitiesfalse conflicts: Txn 1 writes a.x, a.y, Txn 2 reads a.z, and they conflict
field / wordfewer false conflicts, more concurrencymore time and space overhead
cache linematches HTM; less record storagehard for programmers and compilers to reason about

Mixing per type is possible, for example element-level for arrays and object-level for everything else.

Demo 01 measures this directly. tl2.h hashes addresses into 2^20 records with a configurable stripe size, and runs an update-heavy hash-map workload on 8 threads:

stripe (bytes per record)operations per µsaborts per commit
8 (one word)26–290.003
64 (one cache line)230.017
51213–150.053–0.058
4,09611–120.07–0.10

Coarser records mean fewer records to check, but unrelated words that share a record now conflict. At 4 KiB stripes, aborts rose about 30× and throughput fell by more than half.

2.4 An example STM algorithm (slides 17–21)

Slide 17’s STM, after Intel’s McRT, uses eager versioning, optimistic reads and pessimistic writes:

  • a global timestamp, incremented when a writing transaction commits;
  • a local timestamp per transaction: the global value when it last validated;
  • a 32-bit transaction record. Its low bit is 0 if writer-locked, 1 if not. The upper bits hold the version (the timestamp of the last commit) when unlocked, or a pointer to the owning transaction when locked.

The operations (slides 18–19):

  • Read (optimistic). Read the location directly (eager: memory holds current data). Check that its record is unlocked and its version ≤ the local timestamp. If not, validate the whole read set. Add it to the read set.
  • Write (pessimistic). Validate as for a read, then acquire the record’s lock, log the old value in the undo log, and write in place.
  • Read-set validation. Get the global timestamp. For each read-set item, abort if it is locked by someone else or its version is newer than the local timestamp. Then set the local timestamp to the global value read at the start.
  • Commit. Atomically add 2 to the global timestamp (the low bit is reserved for the lock flag). If the old value exceeds the local timestamp, someone committed meanwhile, so validate the read set. Then release every write lock, setting its version to the new timestamp.

Slides 20–21 work an example. X1 copies object foo (version 3, holding [9, 7]) into bar (version 5, holding [0, 0]), field by field, while X2 reads bar.x and bar.y. X2 must see [0, 0] or [9, 7], never a mixture. When X2 finds bar’s record locked by X1, it waits. When it later finds bar’s version newer than when it started reading, it aborts, and its retry sees the committed [9, 7].

tl2.h implements the closely related TL2 (Dice, Shalev and Shavit, 2006). TL2 uses lazy versioning, and locks the write set only at commit:

stepwhat TL2 does
beginrv = global version clock
read xx in our write set? return the buffered value. Else read the record, then x, then the record again; abort if it was locked, changed in between, or has a version > rv
write xappend to the write buffer
commitlock the write set’s records (abort if one is busy); wv = ++clock; if wv ≠ rv + 1, validate every record in the read set (unlocked or ours, version ≤ rv); write the buffer back; release each record with version wv

Every value a TL2 transaction reads was valid at time rv. So a transaction never sees an inconsistent snapshot, and read-only transactions need no validation at commit.

2.5 STM vs. locks, measured

Demo 01 uses a chained hash map: 1,024 buckets, keys 0–4095, 2,048 present at the start. Operations are contains, insert, remove, and a composite move(k1, k2) that removes one key and inserts another atomically. The implementations:

  • no synchronization (one thread only);
  • one global lock;
  • per-bucket spin locks, with move taking two bucket locks in index order;
  • NOrec (Lecture 17, norec.h);
  • TL2.

Every map is checked afterwards. Operations per microsecond, ranges across runs:

1 thread8 threads
read-mostly (90% contains)
no synchronization49–53—
one global lock45–4710–14
per-bucket locks41–44106–117
NOrec STM33–3748–54
TL2 STM25–3166–74
update-heavy (60% updates)
no synchronization36–40—
one global lock31–388–11
per-bucket locks31–3367–83
NOrec STM23–267.5–8.1
TL2 STM20–2225–30

What it shows:

  • Both STMs scale where a global lock collapses, with no lock design at all. Composite operations such as move are just one more atomically { }. On read-mostly work, TL2 at 8 threads ran 5× faster than the global lock.
  • Hand-designed fine-grained locks are still the fastest. Each hash-map operation touches one bucket, which is the ideal case for per-bucket locks. TM’s case is productivity and composability, not beating an expert design.
  • NOrec collapses on updates; TL2 does not. NOrec has no per-location records, so every committing writer passes through one global sequence number, and that serializes writers. TL2’s records let transactions with disjoint write sets commit in parallel. Records cost time per access but buy scalability.

One more lesson came from building the demo. In the first version, both STMs stayed flat as threads were added. Every transaction allocated its logs, so malloc, not the TM algorithm, was the bottleneck. Reusing one transaction descriptor per thread made TL2 6× faster at 8 threads.

2.6 Why is STM slow? (slides 22–30)

Slide 23 lists the challenges for STM systems:

  • the overhead of the barriers;
  • function cloning;
  • robust contention management;
  • the memory model: strong vs. weak atomicity.

Slide 30 measures single-thread STM at 1.8–5.6× slower than sequential code, with most of the time in read barriers and commit, because most applications read much more than they write. Slide 29 shows the consequence: an STM may need many processors just to break even (the Vacation benchmark), which discourages parallel programming and wastes energy.

Demo 01’s single-thread numbers on the read-mostly mix (best of 3) show the same thing, more mildly:

  • NOrec: 1.4–1.6× slower than unsynchronized code;
  • TL2: 1.7–1.8× slower;
  • a global lock: 1.1–1.2× slower.

The overhead is milder than slide 30’s because a hash map’s pointer chasing, mostly cache misses, dominates its time. Each TL2 read also reads a transaction record twice and logs it; each NOrec read logs a (location, value) pair.

Compilers help (slides 24–27). A monolithic barrier like tmWr(&a.x, t1) hides redundancy. Decomposing it into txnOpenForWrite(a) and txnLogObjectInt(&a.x, a) lets the compiler see that a is opened for writing several times. It can then remove redundant opens, logs and locks, hoist barriers out of loops, and skip barriers on transaction-local data. With such optimizations, single-thread overhead fell to under 40% over no concurrency control, and under 30% over lock-based code (slide 27). Slide 28’s exercise shows the steps for atomic { obj.f1 = 42; } in an eager STM with optimistic reads and pessimistic writes:

tx = GetTxDescriptor();
OpenForWriteTx(tx, obj);              // lock obj's record (pessimistic write)
LogForUndoIntTx(tx, obj, offset);     // old value into the undo log (eager versioning)
obj.f1 = 42;                          // write in place

3. Hardware transactional memory (slides 29–49)

3.1 Why hardware, and which kind (slides 29–31)

Software barriers cost 2–8× per thread (slide 29). That is bad for adoption in the short term and wastes energy in the long term. And strong atomicity (isolation from non-transactional code) is costly to provide in software.

Hardware support comes in three kinds (slide 31):

kindexampleswrite versioningconflict detection
hardware-accelerated STMHASTM, SigTM, USTMsoftwarehardware primitives
hardware TMTCC, LTM, VTM, LogTMhardwarehardware (no software barriers)
hybrid TMSun Rockhardware, falling back to an STM when neededhardware or software

3.2 Versions in the cache, conflicts through coherence (slides 32–33)

An HTM reuses the machinery of Lecture 14:

  • Data versioning lives in the caches. The cache holds the write buffer (lazy) or the undo log (eager). New metadata bits track the transaction’s read set and write set. A register checkpoint taken at transaction begin restores the CPU state on abort.
  • Conflict detection rides on the coherence protocol. Coherence lookups detect conflicts between transactions, with snooping or directories.

Each cache line gets an R bit, set by transactional loads, and a W bit, set by transactional stores (slide 33). They can be per word or per line, and they are gang-cleared on commit or abort. A coherence request from another core that hits a marked line is a conflict:

  • a shared request to a W line: read-write;
  • an exclusive request to an R line: write-read;
  • an exclusive request to a W line: write-write.

3.3 A lazy-optimistic HTM, step by step (slides 34–41)

CPU changes:

  • the ability to checkpoint registers;
  • TM state registers (status, abort handler).

Cache changes:

  • the R and W bits.

Demo 02, Part A, runs slide 36’s transaction on core 0: xbegin; load A; load B; store C ⇐ 5; xcommit. It prints each line’s coherence state and its R and W bits:

step           line A     line B     line C      memory C
xbegin           -          -          -         0
load A         S R1 W0      -          -         0
load B         S R1 W0    S R1 W0      -         0
store C <- 5   S R1 W0    S R1 W0    S R0 W1     0
xcommit        S R0 W0    S R0 W0    M R0 W0     5

Slide 39 asks why the store of C is “not a load into exclusive state”. In a lazy design, the store only marks W and keeps the new value in the cache. Other caches may keep their copies, and other transactions may keep reading C’s old value. Exclusive ownership is requested at commit, in a fast two-phase commit (slide 40): first request exclusive access to every write-set line (validate), then gang-clear the R and W bits, which turns the write set into ordinary dirty data.

The abort side (slide 41) runs when another core commits writes to A and D first. Its exclusive request for A arrives, and A is in core 0’s read set:

core 1's exclusive request for line 0x1000 hits core 0's read set
core 0 ABORTS (conflict): W lines invalidated, R bits cleared, registers restored
core 0 commit -> ABORTED (conflict); memory A = 1, C = 0

Aborting means invalidating the write-set lines (the speculative C = 5 disappears), clearing the R bits, and restoring the register checkpoint.

How well does it work? Slide 42 reports HTM 2–7× faster than STM, within 10% of sequential code on one thread, and scaling well.

3.4 The catch: the cache is finite (slide 49)

Intel’s Haswell added Restricted Transactional Memory (RTM, slide 49):

  • xbegin takes a fallback address, the code to run on abort, typically a path with a lock;
  • xend commits;
  • xabort aborts explicitly.

The read and write sets are tracked in the L1 cache, and the processor may abort a transaction for many reasons, for example evicting a line of its read or write set. The implementation does not guarantee progress: software must always have a fallback.

Demo 02 models a Haswell-like L1 (32 KiB, 8-way, 64-byte lines, 64 sets) in “requester wins” mode.

Capacity (Part B), a transaction touching N distinct lines:

N lines8964512513
consecutive lines (loads or stores)okokokokabort
lines 4 KiB apart (all in one set)okabortabortabortabort

512 consecutive lines (exactly 32 KiB) fit. But lines that map to the same set abort after 8, the associativity. A transaction’s size limit depends on its addresses, not just its footprint.

False conflicts (Part C): two cores each increment their own word of one 64-byte line, 200 times each.

  • With R/W bits per line, they caused 200 aborts for 400 commits.
  • With per-word bits, they caused none.

This is Lecture 14’s false sharing in a new form, and it is why slide 33 says the bits “can be at word or cache-line granularity”.

No progress guarantee (Part D): 4 cores each increment one shared counter 30 times.

  • Retrying until success: all 120 increments eventually committed, but one increment needed 91 attempts. Nothing bounds it.
  • A fallback lock after 3 attempts. Each transaction reads the lock word, so a thread taking the lock aborts all of them. Progress is guaranteed, but here 117 of 120 increments ended up on the lock: once one thread falls back, the others abort on the lock word and pile on. This is the “lemming effect”.
  • Waiting outside the transaction until the lock is free before retrying, and not counting that wait as a failed attempt: 69 increments committed in hardware.

Intel’s optimization manual (slide 49) devotes a chapter to keeping transactions from aborting. Intel later disabled TSX on many processors through microcode updates, after both errata and security concerns. IBM shipped HTM in POWER8 and z-series processors. Arm specified the Transactional Memory Extension (TME) in Armv9, but it is rarely implemented. As of this writing, best-effort HTM exists in some hardware but is not something portable software can rely on.

3.5 TCC: transactions all the time (slides 44–48)

Transactional Coherence and Consistency (TCC, Hammond et al., 2004, from Kunle Olukotun’s group at Stanford) takes the idea to its end. Every instruction is part of some transaction, and transaction commits are the coherence mechanism: a successful commit updates memory and all caches. Slide 44’s exercise:

  • Model: lazy versioning, optimistic detection; at most one commit per execution step across all processors; an aborted transaction may begin re-executing in the same step as the commit that aborted it; minimize the number of steps.
  • Programs:
    • P1 runs T1 (read A; write A ← 1; write C ← 2; read D), then T2 (read A; write E ← 3);
    • P2 runs T3 (write C ← 4; read A; write E ← 5);
    • P3 runs T4 (read E; write B ← 6; write C ← 7; read F).

Demo 02, Part E, executes these rules. Its tie-break: the transaction that finished first commits first, then the lowest processor. Highlights of its table:

step 5: P2 commits T3 (writes C:4, E:5)  -> T4 had read E: abort, restart
step 6: P1 commits T1 (writes A:1, C:2)
step 10: P1 commits T2 (writes E:3)       -> T4 (re-run) had read E:5: abort, restart
step 15: P3 commits T4                    -> done; memory A=1, B=6, C=7, E=3

T4 reads E, and E is written by two other transactions, so it aborts twice. In TCC only a read of something a committer wrote causes an abort. Write-write overlaps are simply ordered by commit order (C ends as 7, from the last commit). A different commit order could save steps, which is exactly what the exercise asks students to look for.


4. Transactional memory: summary (slides 43, 50)

  • The atomic construct is a declaration that atomic behaviour must be preserved by the system. The motivating idea is simpler synchronization without significantly sacrificing performance.
  • Many implementations have been proposed: software, hardware, and both. They differ in versioning policy (eager vs. lazy), conflict detection policy (pessimistic vs. optimistic), and detection granularity (object, word, cache line).
  • Software TM: the compiler inserts barriers (instrumentation code). The runtime keeps a descriptor per thread (status, read/write sets) and a record per datum (locked/version).
  • Hardware TM: versioned data is kept in the caches, and conflict detection is built on the coherence protocol.

5. Course wrap-up (slides 51–62)

5.1 Why this course matters (slides 52–54)

For the foreseeable future, the primary way to obtain higher performance computing hardware is through a combination of increased parallelism and hardware specialization.

Slide 52’s gallery shows what that looks like:

  • GPUs with 32-wide SIMD, thousands of threads per core, and tensor cores (Lectures 7, 9–10);
  • heterogeneous phone chips: CPU, GPU and media engines on one die;
  • FPGAs, TPUs and Trainium (Lectures 10–11).

The rest of the argument (slides 53–54):

  • Modern software is surprisingly inefficient compared with what such machines can do, and more so as machines grow more parallel and more complex.
  • Extracting that performance matters for every compute-intensive field, and enables new applications.
  • With today’s tools, getting it requires understanding how a parallel machine works.

These notes measured that gap repeatedly on one laptop:

  • Lecture 1: 8 cores × NEON SIMD × several pipelines against one scalar thread.
  • Lecture 9: Accelerate’s matrix units against a naive matmul.
  • Lecture 13: an 18–20× blur speedup from scheduling alone.

5.2 The key issues, at every scale (slides 55–56)

The course kept returning to the same questions:

  1. Identifying parallelism, or equivalently identifying dependencies: Lectures 2–4 and 8 (data-parallel thinking, scan).
  2. Efficiently scheduling work:
    • balancing the workload: Lecture 5’s static vs dynamic assignment, work stealing;
    • overcoming communication limits: bandwidth (Lectures 3, 6, 12), latency (Lectures 2, 11), synchronization (Lectures 14–18).
  3. Exploiting locality, which means managing state efficiently:
    • caches and blocking: Lectures 6, 9, 13;
    • on-chip memories: Lectures 10–11;
    • coherence and false sharing: Lecture 14.

These issues appeared at every scale the course covered:

  • a single multi-core CPU and its SIMD units;
  • a GPU;
  • CPU + GPU systems and phone chips;
  • AI accelerators;
  • clusters of thousands of accelerators (Lecture 12).

The course also covered how throughput-oriented hardware works: multiple cores, hardware threads, SIMD and specialized accelerators. And it covered the abstractions that help structure efficient code: SPMD (ISPC, CUDA), data-parallel primitives, tasks (Cilk-style fork-join), functional and dataflow programming, DSLs (Halide), and transactions.

5.3 Lessons these notes kept relearning

Running every idea on real hardware produced its own recurring lessons, recorded in each lecture’s “plan vs reality”:

  • Measure, don’t assume. The slides’ tile was 4× slower than the best tile on this machine (Lecture 13). TTAS lost to TAS (Lecture 15). Hand-over-hand locking lost to one global lock (Lecture 16). Lock-free lost to a mutex under contention (Lecture 16).
  • Data movement dominates. Fast code was memory-bound in Lectures 3, 6, 9, 12 and 13, and only less traffic helped.
  • Synchronization costs coherence traffic. A line hand-off costs ~40–90 ns, so every lock, flag and shared counter is a potential serial bottleneck (Lectures 14–16).
  • Correctness needs the model, not just testing. Litmus outcomes that ARM allows but we never observed (Lecture 15), ABA interleavings found only by exhaustive search (Lecture 16), the hazard-pointer window (Lecture 16).
  • The “overhead” you measure may be something else. Thread creation (Lecture 13), malloc in the STM (Lecture 18), first-run page faults, and other programs on the machine.

5.4 Next steps (slides 57–62)

Related Stanford courses (slide 58):

  • CS 217, Hardware Accelerators for Machine Learning: these notes have a companion course folder;
  • CS/EE 282, Computer Systems Architecture;
  • CS 348K, Visual Computing Systems: high-performance systems for images, video, camera pipelines and AI-based graphics. That is Halide’s home ground.

The other course folders in this collection that continue CS149’s threads are:

  • CMU 15-213 (the systems foundation);
  • CMU 15-440 (distributed systems);
  • CMU 11-868 and CMU 15-779 (LLM systems and ML systems);
  • CS 349D (cloud computing).

Slides 59–61 invite students into research. Kayvon’s lab examples include:

  • making LLM agents more efficient without fine-tuning;
  • compiler abstractions for scheduling work onto threads, thread blocks and warps;
  • million-frame-per-second world simulators for training AI agents;
  • AI play-testers for game design;
  • a CS149 assistant agent.

The advice for getting started (slide 60): be highly motivated, have background in the area, go beyond expectations on the course’s programming projects, and be ready to put real time in.


Summary

  • Real TM systems fill the design space. STMs such as TL2, OSTM and McRT, and HTMs such as TCC, LTM/VTM and LogTM, pick different versioning and detection policies. “Optimistic reads, pessimistic writes” is a common compromise.

  • An STM:

    • instruments every transactional access with barriers;
    • keeps a descriptor per thread and a record per datum;
    • maps data to records by embedding or hashing.

    Record granularity trades overhead against false conflicts: 8-byte → 4 KiB stripes gave 30× more aborts in demo 01. TL2 = global version clock + versioned locks + read validation + commit-time locking.

  • STMs are slow on one thread: 1.4–1.8× here, 1.8–5.6× in slide 30, mostly in read barriers and commit. Compiler optimization of decomposed barriers cuts this a lot. On 8 threads, TL2 scaled to 5× a global lock on read-mostly work, but per-bucket locks were faster still. NOrec, with no records, serialized all writers.

  • An HTM keeps speculative data in the cache, marks lines with R/W bits, and detects conflicts with coherence requests. It nearly removes single-thread overhead. But it aborts when a transaction’s lines do not fit (512 consecutive lines, or just 9 in one set). Per-line bits cause false conflicts, and best-effort HTM guarantees no progress, so a fallback path is mandatory (and must avoid the lemming effect).

  • The course in one sentence: performance now comes from parallelism and specialization, and using them well means identifying parallelism, scheduling work against load imbalance and communication costs, and managing locality, at every scale from SIMD lanes to datacenters.

Common pitfalls

  • Benchmarking an STM and measuring the allocator. Allocating descriptors or logs per transaction can dominate. Reuse per-thread structures.
  • Choosing coarse transaction records to save overhead, then losing it all to false conflicts. Object granularity needs objects that are rarely written concurrently.
  • Long read-only transactions in a value-validating STM. NOrec revalidates the whole read set whenever any writer commits, so long readers keep re-doing work. TL2’s per-record versions avoid that, but then the readers abort instead.
  • Assuming hardware transactions always commit eventually. RTM-style HTM may abort for capacity, interrupts, faults or conflicts, forever. Always write the fallback.
  • A fallback lock that is not read inside the transaction. Without subscribing to the lock (reading it in the transaction), a hardware transaction and a lock holder can run concurrently on the same data. And retrying while the lock is held makes everyone fall back (lemming effect).
  • Expecting STMs to beat a good fine-grained lock design. They beat a global lock and save design effort. Per-bucket locks on a hash map were still 1.4–3× faster than TL2.

Exercises

  1. Placing a design. An STM writes in place and locks a record at the first write to it, but validates reads only at commit. Classify it, and name the system on slide 12 that matches.

    AnswerEager versioning, pessimistic detection for writes (locks at the first write), optimistic for reads (validated later): Intel's McRT STM (slide 17). Writing in place requires owning the location first, so writes cannot be optimistic. Reads can be.
  2. Granularity. Txn 1 writes a.x and a.y; Txn 2 reads a.z of the same object. Do they conflict under object-granularity records? Under word granularity? Under 64-byte records, if a is a 24-byte object?

    AnswerObject granularity: yes, a false conflict, since all fields share one record. Word granularity: no, they touch different words. 64-byte records: yes if all three fields fall in the same 64-byte block, which they usually do for a 24-byte object, unless the object straddles a block boundary. That is the "hard to analyze" drawback of cache-line granularity.
  3. TL2 reads. In tl2.h, a read loads the record, then the data, then the record again. What could go wrong if it loaded the record only once, before the data?

    AnswerA writer could commit between the record load and the data load: lock the record, write the new value, release it with a newer version. The reader would then use a new value while having checked an old version, accepting a value from after its snapshot rv as if it were consistent with its other reads. Re-reading the record after the data, and requiring it unchanged and unlocked, proves the value was not overwritten while being read.
  4. Why can TL2’s read-only transactions skip commit-time validation? Contrast with a writer.

    AnswerEach TL2 read already checked that the record's version was ≤ rv, so every value read was the latest committed value as of time rv. Together, the read set forms a snapshot of the memory at rv, so a read-only transaction can serialize at rv. A writer must serialize at its commit time wv. If anyone committed between rv and wv, some value it read might have changed since rv, so it must re-check its read set before writing.
  5. HTM capacity. A transaction walks an array of 100 structs, each 4 KiB apart, reading one field of each. On demo 02’s L1 (32 KiB, 8-way, 64 B lines), does it fit? What about an array of 100 structs 64 bytes apart?

    Answer4 KiB apart: every address maps to the same set (4096 = 64 sets × 64 B), so the 9th line already evicts a read-set line, and the transaction aborts for capacity even though it reads only 100 × 64 B = 6.4 KiB. 64 B apart: 100 consecutive lines spread over the 64 sets, at most 2 lines per set, so it fits.
  6. Lazy vs eager HTM. In the lazy HTM of slides 36–41, a transactional store does not request exclusive ownership. What does the eager design (Intel RTM-like) do instead, and how does that change when conflicts are detected?

    AnswerThe eager design issues the exclusive (read-for-ownership) request at the store, as a normal write would. Any other core whose transaction has the line in its R or W set sees the request immediately and aborts (requester wins). Conflicts are found at the access: pessimistic detection, earlier, with less wasted work, but no forward-progress guarantee. The lazy design finds them only at commit, when the committing core requests its write-set lines.
  7. Fallback paths. Why must a hardware transaction read the fallback lock’s word (lock subscription), and why should it wait for a held lock before retrying instead of immediately counting another failed attempt?

    AnswerSubscription: if the transaction did not read the lock, a thread could take the lock and modify the data non-transactionally while a hardware transaction modifies the same data speculatively, and the two would not be serialized. With the lock word in the read set, taking the lock (a write) aborts every running transaction. Waiting: if a transaction that finds the lock held immediately retries and fails again, it quickly exhausts its attempts and takes the lock itself. Soon every thread runs serially on the lock (the lemming effect: 117 of 120 increments in demo 02). Waiting until the lock is free lets the next attempt run in hardware.
  8. The course in one question. Pick one program from these notes that ran far below the machine’s peak at first. Which of slide 55’s key issues (parallelism, workload balance, communication, locality) explained the gap, and what fixed it?

    AnswerOne example: Lecture 13's 3×3 blur. Scalar two-pass code ran at ~8 GB/s. The fixes, in order: - vectorization (SIMD parallelism); - threads (core parallelism, with dynamic assignment of tiles for balance); - fusing the passes into row chunks (locality: the temporary rows stay in cache, cutting DRAM traffic by half).

    The best version ran at ~200 GB/s, the speed of memory, about 20× faster. Communication (bandwidth) then became the only limit. Other good answers: Lecture 9’s matmul (blocking for locality), Lecture 12’s all-reduce (communication), Lecture 5’s work stealing (balance).

No assignment covers transactional memory. The wrap-up’s message applies to all five:

  • PA1: multi-core and SIMD;
  • PA2: scheduling task graphs;
  • PA3: CUDA rendering;
  • PA4: an AI accelerator;
  • PA5: fast CUDA kernels.

Each is a hands-on instance of identifying parallelism, scheduling, communication and locality on a specific machine.

Further reading

  • The Fall 2025 slides for this lecture.
  • D. Dice, O. Shalev, N. Shavit, “Transactional Locking II”, DISC 2006 (tl2.h).
  • B. Saha, A.-R. Adl-Tabatabai, R. L. Hudson, C. C. Minh, B. Hertzberg, “McRT-STM: A High Performance Software Transactional Memory System for a Multi-Core Runtime”, PPoPP 2006 (slide 17).
  • A.-R. Adl-Tabatabai et al., “Compiler and Runtime Support for Efficient Software Transactional Memory”, PLDI 2006 (slides 24–27).
  • C. Cascaval et al., “Software Transactional Memory: Why Is It Only a Research Toy?”, ACM Queue / CACM 2008: the case against STM’s overheads.
  • L. Hammond et al., “Transactional Memory Coherence and Consistency”, ISCA 2004 (TCC); and “Programming with Transactional Coherence and Consistency (TCC)”, ASPLOS 2004.
  • R. Rajwar, M. Herlihy, K. Lai, “Virtualizing Transactional Memory”, ISCA 2005 (VTM); K. Moore et al., “LogTM”, HPCA 2006.
  • Intel, Intel 64 and IA-32 Architectures Optimization Reference Manual, the chapter on Intel TSX (slide 49).
  • R. M. Yoo, C. J. Hughes, K. Lai, R. Rajwar, “Performance Evaluation of Intel Transactional Synchronization Extensions for High-Performance Computing”, SC 2013.

术语表 (Glossary, English → 中文)

English中文
software transactional memory (STM)软件事务内存
hardware transactional memory (HTM)硬件事务内存
hybrid TM / hardware-accelerated STM混合事务内存 / 硬件加速的软件事务内存
barrier (read / write barrier, STM)屏障函数(读 / 写屏障,STM 插桩)
instrumentation插桩
function cloning函数克隆
transaction descriptor事务描述符
transaction record (ownership record)事务记录(所有权记录)
versioned lock / version number带版本的锁 / 版本号
global timestamp / global version clock全局时间戳 / 全局版本时钟
read version (snapshot time)读版本(快照时间)
read-set validation读集校验
commit-time locking提交时加锁
granularity (object / word / cache line)粒度(对象 / 字 / 缓存行)
false conflict伪冲突
stripe (address range per record)条带(每条记录覆盖的地址范围)
strong / weak atomicity强 / 弱原子性
decomposed barriers分解的屏障
register checkpoint寄存器检查点
R bit / W bit (read / write set bits)读集位 / 写集位
gang-clear批量清零
two-phase commit两阶段提交
capacity abort容量中止
associativity (set-associative cache)相联度(组相联缓存)
Restricted Transactional Memory (RTM) / TSX受限事务内存 / 事务同步扩展
fallback path / lock elision回退路径 / 锁消除
lock subscription锁订阅(在事务中读取锁字)
lemming effect旅鼠效应(争相退回到锁)
Transactional Coherence and Consistency (TCC)事务一致性与一致性(TCC)
heterogeneous system-on-chip (SoC)异构片上系统
hardware specialization硬件专用化
← 返回课程目录