The Loop Is Still Spinning and the Flag Was Set Ten Minutes Ago
Last timeEverybody Waiting
A write can simply never reach another thread. No reordering is involved and no lock would help. This is a separate hazard with a separate cause and a separate fix.
Visibility is not ordering
Everything so far has been about order. Which step ran first, which thread got
the lock, which write landed on top. There is a separate hazard that no amount
of thinking about order will find, and it catches people who have carefully
learned the ordering material.
A write may never become visible to another thread at all. Not late, not in the
wrong order. Never.
shared: a flag, initially false
shared: a message, initially empty
worker thread:
do the work
message = the result
flag = true
waiting thread:
while flag is false:
do nothing
use the message
the waiting thread may loop forever,
even an hour after the flag was set.Nothing here has an ordering problem worth the name. There is exactly one
writer of the flag and exactly one reader. No interleaving produces a wrong
value, because there is only one value it is ever set to. And the loop can
still run forever.
Where the value is sitting
To see why, follow the written value and ask where it physically is at each
moment.
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