ContentsThe library

What Two Threads Can Break

A Perfectly Correct Lock Around Exactly the Wrong Piece of Code

Last timeOne Line Is Not One Step

A lock lets one thread at a time into a region. Choosing the region is the whole skill, and the usual mistake is a flawless lock that leaves the broken state visible anyway.

What a lock promises

A lock makes exactly one promise. At most one thread is inside the protected

region at a time. A thread that arrives while another is inside waits until the

first leaves.

Read that again for what it does not say. It says nothing about the data. It

says nothing about threads that touch the same data without taking this lock.

It says nothing about threads holding a different lock. The guarantee is about

a region of code and about nothing else.

FIG 1A thread arriving at a lock
The two branches out of the first node are the whole picture. The left one is the discipline working. The right one is what happens when any single piece of code touches the data without participating, and it is not prevented by anything.

That last branch is worth dwelling on. A lock is a convention among the pieces

of code that agree to use it. The data itself is not protected and cannot tell

anyone off. One accessor that reads the data without taking the lock defeats the

entire arrangement, and it is usually a reader added later by somebody who

reasoned that reading cannot break anything.

The region is the invariant

Here is the question that determines where the region goes: what is supposed to

be true at all times?

The lesson stops here

5 more paragraphs to go

You have read the opening. The rest of the argument, the problems that check whether it landed, and the lines worth keeping at the end all come with a plan.

The first lesson of every course in the library reads the whole way through, free, so you can see exactly what the rest of them are.

See the planThe contents

This is the reading half

Starting the course gives you your own copy of it. Every idea on every page has problems standing under it, marked with a reason rather than a tick, and any sentence you do not believe can be opened and argued with. None of that can happen on a page nobody owns.

The contents

The rest of this course

  1. 01Two Threads, Four Steps, and Six Different Programs You Did Not Write
  2. 02The Statement You Wrote Is Three Instructions and the Danger Lives Between Themopening only
  3. 03A Perfectly Correct Lock Around Exactly the Wrong Piece of Codeyou are here
  4. 04Four Things Must All Be True, So Breaking Any One of Them Is Enoughopening only
  5. 05The Loop Is Still Spinning and the Flag Was Set Ten Minutes Agoopening only
  6. 06One Relation Settles Every Argument About What a Thread Is Allowed to Seeopening only
  7. 07Write It Only If Nobody Moved It, and Try Again If They Didopening only
  8. 08Seven Lessons of Difficulty That All Disappear If Nobody Shares Anythingopening only

Read alongside