CKTIS / C
atomic_exchange — C23 atomic generic function
`atomic_exchange(object, desired)` from `<stdatomic.h>` performs one atomic read-modify-write operation: it stores `desired` in `*object` and returns the value the object held immediately before the exchange.
Version: C23
Syntax
C atomic_exchange(volatile A *object, C desired);atomic_exchange(object, desired) from <stdatomic.h> performs one atomic read-modify-write operation: it stores desired in *object and returns the value the object held immediately before the exchange.
Use it to take ownership of an atomic state or pointer when the previous owner is needed in the same linearizable step. The example really changes 5 to 9; it returns 5, while the later atomic_load reads 9.
object must point to a compatible, properly initialized atomic object, and the operation need not be lock-free. The non-_explicit form uses memory_order_seq_cst. The return is the old value, not the new one, and exchanging one object does not by itself synchronize unrelated data without a correct memory protocol.
This generic function name may be a macro or an external identifier; suppressing the macro to call an actual function, or defining an external identifier with that name, has undefined behavior.
Examples
#include <stdatomic.h>
#include <stdio.h>
int main(void) {
atomic_int value = 5;
int previous = atomic_exchange(&value, 9);
printf("%d %d\n", previous, atomic_load(&value));
return 0;
}
Result
5 9
Use it to take ownership of an atomic state or pointer when the previous owner is needed in the same linearizable step. The example really changes `5` to `9`; it returns `5`, while the later `atomic_load` reads `9`.