I remember that at some point, I saw a programming challenge where people were asked to atomically read a double word with single-word operations.
Now, before we go on, a few clarifications:
- A single word is a unit that has the natural number of bits that can be processed by some processor (for instance, 32 bits for 32-bit processors);
- A double word is a unit that is twice the size of a single word (and therefore can't be treated at once by processor instructions);
- By atomic, I mean that the result data should be consistent with what the value was at some point, and we can assume that no implementation or hardware detail will get in the way.
As I recall it, the solution was to read the highest word, then read the lowest word. Then read again the highest word, and if it hasn't changed, then the value can be deemed consistent.
However, I'm not sure anymore. Suppose that we have the two digits 01
.
- The algorithm would then read the high part (and get
0
). - Now, another actor changes the value to
22
before our algorithm reads the next part. - We then read the low digit,
2
; - but then, the pesky troublemaker changes the value again, and makes it
03
. - We read the high part, and it's
0
. We read02
, and the algorithm deems the value consistent; but in fact, it never was02
.
Is my recollection of the conundrum correct? Is it the solution that I don't recall correctly?