Skip to the guide

Atomics and compare-and-swap

IntermediateConcept6 pages

An atomic is a variable whose single operations can't be interrupted, so one counter or one reference needs no lock. Compare-and-swap, or CAS, is the operation behind it: set this value only if it still holds what I saw. The interviewer asks when an atomic is enough and when you need a lock, and the answer depends on how many things must change together.

Today's special in a frame

A restaurant has a turnstile at the door and a frame by the entrance that holds today's special. The turnstile counts people, and each push moves the counter by exactly one, so two people pushing in turn can't lose a count.

The special is harder. Suppose the dish and the price sit in two separate frames. A customer who walks past while the waiter is halfway through sees the new dish with yesterday's price. So the restaurant writes both on one card and keeps one frame, and changing the card is a single movement.

Two waiters may still change it on one day, so the rule is this. Before you write a new card, note which card is in the frame. Write yours, go back, and swap only if the same card is still there. If it has changed, you read the new one and start again.