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