function
<atomic>

std::atomic_compare_exchange_weak

template (1)
template <class T>bool atomic_compare_exchange_weak (volatile atomic<T>* obj, T* expected, T val) noexcept;template <class T>bool atomic_compare_exchange_weak (atomic<T>* obj, T* expected, T val) noexcept;
overloads (2)
bool atomic_compare_exchange_weak (volatile A* obj, T* expected, T val) noexcept;bool atomic_compare_exchange_weak (A* obj, T* expected, T val) noexcept;
Compare and exchange contained value (weak)
Compares the contents of the value contained in obj with that of 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.

Unlike atomic_compare_exchange_strong, this weak version is allowed to fail spuriously by returning false even when *expected indeed compares equal to the value contained in obj. This may be acceptable behavior for certain looping algorithms, and may lead to significantly better performance on some platforms. On these spurious failures, the function returns false while not modifying expected.

For non-looping algorithms, atomic_compare_exchange_strong is generally preferred.

See atomic::compare_exchange_weak 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 (and does not fail spuriously).
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