std::atomic...hange_strong(3)
πΈ NAME πΈ
okay so bestie, this page is std::atomic...hange_strong(3) from the C++ Standard Libary (yes, thatβs the manual name, weβre not fixing the spelling, periodt π
). Itβs all about std::atomic::compare_exchange_weak,std::atomic::compare_exchange_strong β the atomic compare-and-swap girlies. π
β¨ Synopsis β¨
Hereβs the whole overload lineup, no cap. All of these are (since C++11) and all are noexcept:
(1) (since C++11)
bool compare_exchange_weak( T& expected, T desired,
std::memory_order success,
std::memory_order failure ) noexcept;
(2) (since C++11)
bool compare_exchange_weak( T& expected, T desired,
std::memory_order success,
std::memory_order failure ) volatile noexcept;
(3) (since C++11)
bool compare_exchange_weak( T& expected, T desired,
std::memory_order order =
std::memory_order_seq_cst ) noexcept;
(4) (since C++11)
bool compare_exchange_weak( T& expected, T desired,
std::memory_order order =
std::memory_order_seq_cst ) volatile noexcept;
(5) (since C++11)
bool compare_exchange_strong( T& expected, T desired,
std::memory_order success,
std::memory_order failure ) noexcept;
(6) (since C++11)
bool compare_exchange_strong( T& expected, T desired,
std::memory_order success,
std::memory_order failure ) volatile noexcept;
(7) (since C++11)
bool compare_exchange_strong( T& expected, T desired,
std::memory_order order =
std::memory_order_seq_cst ) noexcept;
(8) (since C++11)
bool compare_exchange_strong( T& expected, T desired,
std::memory_order order =
std::memory_order_seq_cst ) volatile noexcept;
So whatβs the vibe? It atomically compares the object representation (until C++20) / value representation (since C++20) of *this with that of expected. If those are bitwise-equal, it replaces the former with desired β thatβs the read-modify-write operation π
. Otherwise, it loads the actual value stored in *this into expected β thatβs the load operation. Slay.
Hereβs the memory-order tea β:
- Overloads
(1,2,5,6): the read-modify-write operation usessuccess; the load operation usesfailure. - Overloads
(3,4,7,8): the read-modify-write operation usesorder; the load operation uses:std::memory_order_acquireiforderisstd::memory_order_acq_relstd::memory_order_relaxediforderisstd::memory_order_release- otherwise
order
β οΈ Iffailureis stronger thansuccess, or(until C++17)is one ofstd::memory_order_releaseandstd::memory_order_acq_rel, the behavior is undefined. Like, bestie, do not do that. π
π« It is deprecated ifstd::atomic<T>::is_always_lock_freeis false and(since C++20)anyvolatileoverload participates in overload resolution.
π Parameters π
expectedβ reference to the value expected to be found in the atomic objectdesiredβ the value to store in the atomic object if it is as expectedsuccessβ the memory synchronization ordering for the read-modify-write operation if the comparison succeedsfailureβ the memory synchronization ordering for the load operation if the comparison failsorderβ the memory synchronization ordering for both operations
π Return value π
true if the underlying atomic value was successfully changed, false otherwise. Simple as that, fr fr.
π§ Notes π§
- The comparison and copying are bitwise (similar to
std::memcmpandstd::memcpy); no constructor, assignment operator, or comparison operator are used. compare_exchange_weakis allowed to fail spuriously, that is, acts as if*this != expectedeven if they are equal. When a compare-and-exchange is in a loop,compare_exchange_weakwill yield better performance on some platforms.- When
compare_exchange_weakwould require a loop andcompare_exchange_strongwould not,compare_exchange_strongis preferable unless the object representation ofTmay include padding bits,(until C++20)trap bits, or offers multiple object representations for the same value (e.g. floating-point NaN). In those cases,compare_exchange_weaktypically works because it quickly converges on some stable object representation. - For a union with bits that participate in the value representations of some members but not the others, compare-and-exchange might always fail because such padding bits have indeterminate values when they do not participate in the value representation of the active member.
- Padding bits that never participate in an objectβs value
(since C++20)representation are ignored.
π¦ Example π¦
Compare-and-exchange operations are often used as basic building blocks of lock-free data structures. Iconic behavior, honestly. π
// Run this code
#include <atomic>
template<typename T>
struct node
{
T data;
node* next;
node(const T& data) : data(data), next(nullptr) {}
};
template<typename T>
class stack
{
std::atomic<node<T>*> head;
public:
void push(const T& data)
{
node<T>* new_node = new node<T>(data);
// put the current value of head into new_node->next
new_node->next = head.load(std::memory_order_relaxed);
// now make new_node the new head, but if the head
// is no longer what's stored in new_node->next
// (some other thread must have inserted a node just now)
// then put that new head into new_node->next and try again
while (!head.compare_exchange_weak(new_node->next, new_node,
std::memory_order_release,
std::memory_order_relaxed))
; // the body of the loop is empty
// Note: the above use is not thread-safe in at least
// GCC prior to 4.8.3 (bug 60272), clang prior to 2014-05-05 (bug 18899)
// MSVC prior to 2014-03-17 (bug 819819). The following is a workaround:
// node<T>* old_head = head.load(std::memory_order_relaxed);
// do
// {
// new_node->next = old_head;
// }
// while (!head.compare_exchange_weak(old_head, new_node,
// std::memory_order_release,
// std::memory_order_relaxed));
}
};
int main()
{
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
}
Demonstrates how std::compare_exchange_strong either changes the value of the atomic variable or the variable used for comparison.
Incomplete section alert:This section is incompleteReason: more practical use of the strong CAS would be nice, such as where Concurrency in Action uses it
// Run this code
#include <atomic>
#include <iostream>
std::atomic<int> ai;
int tst_val = 4;
int new_val = 5;
bool exchanged = false;
void valsout()
{
std::cout << "ai = " << ai
<< " tst_val = " << tst_val
<< " new_val = " << new_val
<< " exchanged = " << std::boolalpha << exchanged
<< '\n';
}
int main()
{
ai = 3;
valsout();
// tst_val != ai ==> tst_val is modified
exchanged = ai.compare_exchange_strong(tst_val, new_val);
valsout();
// tst_val == ai ==> ai is modified
exchanged = ai.compare_exchange_strong(tst_val, new_val);
valsout();
}
Output:
ai = 3 tst_val = 4 new_val = 5 exchanged = false
ai = 3 tst_val = 3 new_val = 5 exchanged = false
ai = 5 tst_val = 3 new_val = 5 exchanged = true
π₯ See also π₯
atomic_compare_exchange_weak(C++11)β function templateatomic_compare_exchange_weak_explicit(C++11)β function templateatomic_compare_exchange_strong(C++11)β function templateatomic_compare_exchange_strong_explicit(C++11)β function template
All of these atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not (function template). Obsessed. β¨
π·οΈ Category π·οΈ
* Todo with reason
xoxo, your fave manpage bestie π β source: http://cppreference.com, version/date: 2024.06.10, page: std::atomic...hange_strong(3).
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms