Perform an atomic compare and exchange operation with sequentially consistent memory ordering.
- Parameters
-
index | The index of the array element that will be atomically modified. |
oldValue | A pointer to the expected value of the indexed element. |
newValue | The value to replace the indexed element with. |
- Returns
- If the operation is successful, true is returned. Otherwise, oldValue is replaced with the current value of the indexed element, the element is not modified, and false is returned. In either case, oldValue becomes the value that was originally in the indexed element.
This operation is typically used in a loop. For example usage, an atomic multiplication may be implemented using compare-exchange as follows:
AtomicArrayExecutionObject<vtkm::Int32> atomicArray = ...;
do {
newVal = current * multFactor;
} while (!atomicArray.CompareExchange(idx, ¤t, newVal));
The while condition here updates newVal what the proper multiplication is given the expected current value. It then compares this to the value in the array. If the values match, the operation was successful and the loop exits. If the values do not match, the value at idx was changed by another thread since the initial Get, and the compare-exchange operation failed – the target element was not modified by the compare-exchange call. If this happens, the loop body re-executes using the new value of current and tries again until it succeeds.
Note that for demonstration purposes, the previous code is unnecessarily verbose. We can express the same atomic operation more succinctly with just two lines where newVal is just computed in place.
while (!atomicArray.CompareExchange(idx, ¤t, current * multFactor));