std::atomic_ref<T>::atomic_ref
来自cppreference.com
| (1) | (C++26 起为 constexpr) | |
| (2) | (C++26 起为 constexpr) | |
构造新的 atomic_ref 对象。
1) 构造引用对象
obj 的 atomic_ref 对象。 如果
obj 未对齐到 required_alignment,那么行为未定义。2) 构造引用
ref 所引用对象的 atomic_ref 对象。参数
| obj | - | 所引用的对象 |
| ref | - | 要复制的另一 atomic_ref 对象
|
示例
本程序使用几个线程来增加容器中的各值。然后打印最终的和。非原子访问可能因数据竞争而“丢失”一些运算的结果。
运行此代码
#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; // 原子读-改-写操作
}
};
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);
}
可能的输出:
sum = 40000000
sum = 39994973