From the need of predictable synchronous access to code, the need for a single instruction to read and read a write values arose. There is an instruction to do so, that are called atomic memory exchange.

Non-testable

It is also sometimes called compare-and-swap. In C++, the library related to the set of atomic exchange instructions is std::atomic. In C, this would involve plugging into some assembly. In x86 it would be the XCHG instruction and CMPXCHG.

Use

Atomic memory exchange instructions read and write data in a single instruction. They effectively group the load and store instruction together atomically. This results in an exchange of values in between the register and the memory location.

Because the atomic memory exchange always happens as a single instruction, and it exchanges values we can tell when a write has been successful or not.

For example, if we have a value in memory of 1, and we want to write 0 to it. Two threads attempt to do so with an atomic memory exchange. The first thread to succeed will return with a 1. The second thread that failed will return with a 0, since it will have just exchanged 0 with 0.

This enables the implementations of synchronization primitives for threads like semaphores and locks.

Implementation

Atomic memory exchange is a hardware-level implementation. It cannot be implemented in the CPU alone, as it must be able to synchronize across multiple CPU, since multiple cores can access the same location in memory at the same time.

It is usually implemented by the memory bus. The memory bus synchronizes every CPU’s access to memory. The bus couples both parts of the exchange (the read and write) and ensures that no other transaction intervenes in the meantime.

Drawbacks

This however comes with higher overhead, and is slower than normal load and store instructions.