Question

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.

  1. The algorithm would then read the high part (and get 0).
  2. Now, another actor changes the value to 22 before our algorithm reads the next part.
  3. We then read the low digit, 2;
  4. but then, the pesky troublemaker changes the value again, and makes it 03.
  5. We read the high part, and it's 0. We read 02, and the algorithm deems the value consistent; but in fact, it never was 02.

Is my recollection of the conundrum correct? Is it the solution that I don't recall correctly?

Was it helpful?

Solution

That solution sounds like it was meant for a system where the value was constantly incrementing or decrementing, rather than arbitrarily changing.

By reading high/low/high in a system where the value is incrementing, you can be sure that the value hasn't wrapped, such as (for a one-digit word) 0,9 becoming 1,0. The code would be something like:

read high into reg2                 # Get high value.
set reg0 to reg2 minus 1            # Force entry in to loop.
while reg0 is not equal to reg2:    # Repeat until consecutive highs are same.
    set reg0 to reg2                    # Transfer high.
    read low into reg1                  # Read low.
    read high into reg2                 # Read next high.

# Now reg0/reg1 contains high/low.

In any other situation where the value can arbitrarily change, you need some sort of test-and-set operation on a separate word, effectively implementing a low-level mutex to protect the double-word.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top