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)
atomic_ref
オブジェクトを構築し、オブジェクト
obj
を参照します。
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