Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Compare And Swap good for?

I was recently reading about the Compare And Swap atomic action (CMPXCHG, .NET's Interlocked.CompareExchange, whatever).

I understand how it works internally, and how it's used from a client.

What I can't quite figure out is when would someone use CAS?

Wikipedia says:

CAS is used for implementing synchronization primitives like semaphores and mutexes, likewise more sophisticated lock-free and wait-free algorithms.

So, can anyone give me a more generic real-world use case with code and description of CAS usage?

This question is meant to be language-agnostic, so any language will do (C-based or x86 assembly preferred).

Thanks!

like image 827
Stanislav Nedelchev Avatar asked Apr 24 '12 08:04

Stanislav Nedelchev


People also ask

What is compare and swap used for?

Compare and swap is a technique used when designing concurrent algorithms. The approach is to compare the actual value of the variable to the expected value of the variable and if the actual value matches the expected value, then swap the actual value of the variable for the new value passed in.

Why is compare and swap better than test and set?

test-and-set modifies the contents of a memory location and returns its old value as a single atomic operation. compare-and-swap atomically compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value.

What is a CAS operation?

Computer Assisted Surgery (CAS) In some spine surgeries, CAS tools give surgeons a three-dimensional view of the operation and use a technology similar to a global positioning system (GPS) to provide more accurate targeting and measurement than ever before possible.

How many parameters are passed in compare and swap instruction?

In comparison to Test and Set Instruction, the compare and swap instruction operates on three operands. Here the operand value is assigned to a new value only if the expression (*value == expected) is true.


1 Answers

This is easy to see by example. Say we want to atomically and concurrently set a bit on a shared variable:

int shared = 0;

void Set(int index) {
 while (true) {
  if (Interlocked.CompareExchange<int>(ref shared, shared | (1 << index), shared) == shared)
   break; //success
 }
}

We detect failure if we see that the "old value" (which is the return value) has changed in the meantime.

If this did not happen we did not have a concurrent modification so our own modification went through successfully.

You can realize pretty complex stuff using this technique. The more complex the more performance loss through spinning, though.

I want to emphasize that a key property of CAS is that it can fail and that failure can be detected reliably.

like image 184
usr Avatar answered Sep 21 '22 13:09

usr