On an Intel x86 processor, is it possible to compare one value with another at a particular memory location, resetting the memory if the compare succeeded without worrying about multi-thread/processor issues? I see the instruction CMPXCHG - would that work? Or is there something for a compare-and-set use case?
1 Answers
The CMPXCHG instruction compares the value in an implied register (EAX) with the destination and updates the zero flag (EFLAGS.ZF) to indicate whether the value in the destination matched the value given in EAX in which case the value in the source operand (an explicit register) is stored in the destination. CMPXCHG also updates EAX with the value read from the destination.
Wikipedia describes compare-and-set
as a variant of compare-and-swap
where you get a true/false indication of whether the data at the memory location matched the given value, and therefore whether the memory location was updated. The compare-and-swap
alternative returns the contents read from memory and you can compare with the given value yourself.
http://en.wikipedia.org/wiki/Compare-and-set
... redirects to
http://en.wikipedia.org/wiki/Compare-and-swap
In this sense CMPXCHG is both a compare-and-set
and a compare-and-swap.
You must use the LOCK
prefix to ensure CMPXCHG is executed atomically, that is, the thread executing CMPXCHG gets to read and then write the memory location before any other thread gets access to it.
You say resetting the memory if the compare succeeded
if you mean setting the memory location to zero then zero is the value you want in the source register.
For portable ways of doing a compare-and-swap
see resources in this SO question
Note the CMPXCHG instruction allows the destination operand to be a register as well as a memory location. When testing 8 bytes, you would use the CMPXCHG8B instruction. There is a bug in the Pentium processor when you specify a LOCK
prefix on the CMPXCHG8B instruction and you specify a register as the destination, you can read more about it here

- 11,314
- 33
- 45
-
Do you have any links to the difference between compare and swap, and compare and set? – Evan Carroll Oct 20 '18 at 19:45
-
@EvanCarroll I have updated the answer to include a link to Wikipedia's compare-and-set article, which redirects to compare-and-swap. I have also updated the description of the CMPXCHG instruction, which was wrong. Thank you. – amdn Oct 20 '18 at 23:21