std::atomic...::atomic_ref(3)
π NAME π
std::atomic_ref::atomic_ref β literally std::atomic_ref::atomic_ref, the constructor bestie. The NAME line is giving std::atomic_ref::atomic_ref - std::atomic_ref::atomic_ref, and we are obsessed. π
okay so this is std::atomic...::atomic_ref(3) from the C++ Standard Libary zone, and it's all about making an atomic_ref π
β¨ Synopsis β¨
Both of these are tagged (since C++20), no cap:
explicit atomic_ref( T& obj ); (1) (since C++20)
atomic_ref( const atomic_ref& ref ) noexcept; (2) (since C++20)
Constructs a new atomic_ref object. β¨
- Constructs an
atomic_refobject referencing the objectobj. The behavior is undefined ifobjis not aligned torequired_alignment. π This is not a vibe-check you want to fail, bestie. - Constructs an
atomic_refobject referencing the object referenced byref.
πΈ Parameters πΈ
objβ object to referencerefβ anotheratomic_refobject to copy from
π¦ Example π¦
The program increments the values in a container using several threads. Then the final sum is printed. Non-atomic access may "loss" the results of some operations due to data-races. π
Non-atomic access may "loss" the results of some operations due to data-races.
// Run this code
#include <atomic>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>
int main()
{
using Data = std::vector<char>;
auto inc_atomically = [](Data& data)
{
for (Data::value_type& x : data)
{
auto xx = std::atomic_ref<Data::value_type>(x);
++xx; // atomic read-modify-write
}
};
auto inc_directly = [](Data& data)
{
for (Data::value_type& x : data)
++x;
};
auto test_run = [](const auto Fun)
{
Data data(10'000'000);
{
std::jthread j1{Fun, std::ref(data)};
std::jthread j2{Fun, std::ref(data)};
std::jthread j3{Fun, std::ref(data)};
std::jthread j4{Fun, std::ref(data)};
}
std::cout << "sum = " << std::accumulate(cbegin(data),
cend(data), 0) << '\n';
};
test_run(inc_atomically);
test_run(inc_directly);
}
π Possible output: π
sum = 40000000
sum = 39994973
source/version check, bestie: http://cppreference.com Β· 2024.06.10 Β· std::atomic...::atomic_ref(3) β that's the whole tea π«Άπ
π₯
π¦ 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