The Statement You Wrote Is Three Instructions and the Danger Lives Between Them
Last timeAll the Orders It Could Run In
An increment reads, adds and writes. The scheduler may switch between any two of those. This lesson locates the gap exactly and says which operations have no gap at all.
One line, several steps
The previous lesson treated the increment as two steps, a read and a write,
because that was enough to show the lost update. The real decomposition has
three, and the third one explains something the two-step version does not.
source, one line:
counter = counter + 1
what the machine does:
1 load counter into register r
2 add 1 to register r
3 store register r back into counter
between step 1 and step 3 the shared
counter is not being held by anybody.
any other thread may read it, change
it, and write it back.The add is the giveaway. A thread performing it is working on data it fetched
at some earlier moment and is not looking at the shared location. The length of
that period is not a property of the source line, it is a property of what the
processor and the scheduler happen to do, and it can be a few cycles or several
milliseconds if the thread is preempted in the middle.
Where the gap is
Say exactly what interval is dangerous, because being vague about it is what
leads to the two wrong fixes people reach for first.
The lesson stops here
4 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