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.
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 new value. If not, do nothing. In either case, return the original value at that memory location, thus allowing the code calling compare-and-swap to know whether it succeeded or not.
Building a spin lock
With the compare-and-swap instruction, you can build a lock in a manner quite similar to that with test-and-set. For example, you could just replace the lock()
routine above with the following:
void lock(lock_t *lock) {while (CompareAndSwap(&lock->flag, 0, 1) == 1); // spin}
The rest of the code is the same as the test-and-set example in a previous lesson. This code works quite similarly; it simply checks if the flag is 0 and if so, atomically swaps in a 1 thus acquiring the lock. Threads that try to acquire the lock while it is held will get stuck spinning until the lock is finally released.
If you want to see how to really make a C-callable x86-version of compare-and-swap, the code sequence (
Finally, as you may have sensed, compare-and-swap is a more powerful instruction than test-and-set. We will make some use of this power in the future when we briefly delve into topics such as
Get hands-on with 1400+ tech skills courses.