function
<atomic>

std::atomic_compare_exchange_strong

template (1)
template <class T>
bool atomic_compare_exchange_strong (volatile atomic<T>* obj, T* expected, T val) noexcept;
template <class T>
bool atomic_compare_exchange_strong (atomic<T>* obj, T* expected, T val) noexcept;
overloads (2)
bool atomic_compare_exchange_strong (volatile A* obj, T* expected, T val) noexcept;
bool atomic_compare_exchange_strong (A* obj, T* expected, T val) noexcept;
Compare and exchange contained value (strong)
Compares the contents of the value contained in obj with the value pointed by expected:
- if true, it replaces the contained value with val.
- if false, it replaces the value pointed by expected with the contained value .

The function always accesses the contained value to read it, and -if the comparison is true- it then also replaces it. But the entire operation is atomic: the value cannot be modified by other threads between the instant its value is read and the moment it is replaced.

Note that this function compares directly the physical contents of the contained value with the contents of expected; This may result in failed comparisons for values that compare equal using operator== (if the underlying type has padding bits, trap values, or alternate representations of the same value), although this comparison shall converge rapidly in a loop that preserves expected such as those generally used with atomic_compare_exchange_weak.

Unlike atomic_compare_exchange_weak, this strong version is required to always return true when expected indeed compares equal to the contained object, not allowing spurious failures. However, on certain machines, and for certain algorithms that check this in a loop, compare_exchange_weak may lead to significantly better performance.

See atomic::compare_exchange_strong for the equivalent member function of atomic.

Parameters

obj
Pointer to an atomic object.
Type A represents other overloaded atomic types (if the library does not implement the C-style atomic types as instantiations of atomic).
expected
Pointer to an object whose value is compared to the contained value, and which -in case it doesn't match- may be overwritten with the contained value.
T is the type of the value contained in the atomic object (atomic's template parameter).
val
Value to copy to the contained object in case expected matches the contained value.
T is the type of the value contained in the atomic object (atomic's template parameter).

Return value

true if *expected compares equal to the contained value.
false otherwise.

Data races

No data races (atomic operation). The operation uses sequential consistency (memory_order_seq_cst).

Exception safety

No-throw guarantee: never throws exceptions.

See also