javamultithreadingcpu-architectureatomiccompare-and-swap

Understanding synchronization with multiple processors


In JCIP Section 15.2 B. Goetz mentioned that in modern processors there was a set of instructions like compare-and-swap (CAS) which allowed us to perform non-blocking update operations.

In particular he said

CAS has three operands - a memory location V on which to operate, the expected old value A, and the new value B. CAS atomically updates V to the new value B, but only if the value in V matches the expected old value A.

Now consider a multiprocessor system. If two different processors try to compare-and-swap at the exactly same time on the same memory location, what will happen than?

The processors do not know about each other. How does such a situation manage?


Solution

  • CAS operations in the end rely on specific hardware instructions, so the actual implementation is hardware-specific. If you want to learn about the details, you need to check the specific architecture on which you're running.