std::atomic_ref<T>:: atomic_ref
From cppreference.net
<
cpp
|
atomic
|
atomic ref
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::atomic_ref
| Member functions | ||||
|
atomic_ref::atomic_ref
|
||||
|
(C++26)
|
||||
|
Operations for arithmetic types
(except
bool
and pointer-to-object)
|
||||
|
Operations for integral types
(except
bool
and pointer-to-object)
|
||||
|
(C++26)
|
||||
|
(C++26)
|
||||
|
Operations for integral types
(except
bool
)
|
||||
| Constants | ||||
|
explicit
atomic_ref
(
T
&
obj
)
;
|
(1) | (自 C++26 起为 constexpr) |
|
atomic_ref
(
const
atomic_ref
&
ref
)
noexcept
;
|
(2) | (自 C++26 起为 constexpr) |
构造一个新的
atomic_ref
对象。
1)
构造一个引用对象
obj
的
atomic_ref
对象。
2)
构造一个
atomic_ref
对象,该对象引用由
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; // 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); }
可能的输出:
sum = 40000000 sum = 39994973