Compare and exchange

The human mind was not designed to cope with the atomic compare-and-exchange instruction:

The compare and exchange instruction compares the value in the second register with the value in memory pointed to by the address in the first register. If they are equal, the value in the destination register is swapped with the value in memory pointed to by the address in the first register. If they are not equal, then the value in memory pointed to by the address in the first register is copied into the destination register, but memory is left unchanged.

Go on, try reading that. I guarantee your eyes will glaze over by about halfway through the second sentence. Now, imagine you’ve got to implement that, but you’ve got to do it in terms of what another processor believes is a compare-and-exchange instruction, which is almost – but not quite – exactly the same. Oh, and it has implicit operands. The stream of logic in my head this morning has been running along the lines of:

Sooo…. if the first subject operand is in EAX and the result is also going to be written to EAX, then in the case where the second register is equal to the value in memory we have to swap the operands around so that the implicit second operand on the target side is in the right place which means that register management will believe the output is in a different place which means… where was I again?

Thankfully, though, I managed to maintain a train of thought for long enough to understand what was going on and make it work. It’s only taken about 2 days. Go me.

One Response to “Compare and exchange”

  1. JV says:

    I’m worried that that made sense to me. I think I’ve not understood it.