ELI5: Explain Like I'm 5

Compare-and-swap

Imagine you and your friend both have one toy car. You want to trade your toy car with his toy car. But, you want to make sure that neither of you is tricking the other person. So, you come up with a plan where you both show your cars to each other at the same time and then swap them at the same time. This is kind of like compare-and-swap.

In computer science, compare-and-swap is a way for multiple processes or threads to safely update shared data by making sure no other process has changed it in the meantime. It works like this:

1. You have some shared data, like a number or a piece of text, that multiple processes may want to change.
2. Each process reads the current value and remembers it.
3. Each process then submits a new value it wants to update with.
4. The compare-and-swap operation checks to see if the shared data has changed since the process last read it. If not, the new value is written. If it has changed, the operation is retried until the process writes the new value successfully.

This helps prevent race conditions, where two processes are competing to update the same data at the same time and may cause errors. The compare-and-swap operation ensures that only one process can successfully update the shared data.