Search⌘ K

Compare-And-Swap

Learn how the compare-and-swap instruction works in concurrency control. Understand how it atomically compares and updates memory, enabling the creation of spin locks. This lesson explains its role in synchronization and its advantages over simpler locking methods.

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.

C
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 ...