__compare_and_swap, __compare_and_swaplp
Purpose
Conditionally updates a single word or doubleword variable atomically.
Prototype
int __compare_and_swap (volatile int* addr, int* old_val_addr, int new_val);
int __compare_and_swaplp (volatile long* addr, long* old_val_addr, long new_val);
Parameters
- addr
- The address of the variable to be copied. Must be aligned on a 4-byte boundary for a single word and on an 8-byte boundary for a doubleword.
- old_val_addr
- The memory location into which the value in addr is to be copied.
- new_val
- The value to be conditionally assigned to the variable in addr,
Return value
Returns true (1) if the value in addr was equal to old_value and has been set to the new value. Returns false (0) if the value in addr was not equal to old_value and has been left unchanged. In either case, the contents of the memory location specified by addr are copied into the memory location specified by old_val_addr.
Usage
The __compare_and_swap
function
is useful when a single word value must be updated only if it has
not been changed since it was last read. If you use __compare_and_swap
as
a locking primitive, insert a call to the __isync
built-in
function at the start of any critical sections.
__compare_and_swaplp
is
valid only in 64-bit mode.
This function generates the hardware instruction but does not act as an
instruction movement barrier within the compiler. If that is needed, you must also use the
__fence
function.