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.
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 contentsThis 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