Compare-And-Swap

Let's look at compare-and-swap hardware primitive for supporting locks, in this lesson.

We'll cover the following...

Another hardware primitive that some systems provide is known as the compare-and-swap instruction (as it is called on SPARC, for example), or compare-and-exchange (as it called on x86). The C pseudocode for this single instruction is given in the code excerpt below.

Press + to interact
int CompareAndSwap(int *ptr, int expected, int new) {
int original = *ptr;
if (original == expected)
*ptr = new;
return original;
}

The basic idea is for compare-and-swap to test whether the value at the address specified by ptr is equal to expected; if so, update the memory location pointed to by ptr with the ...