Namespaces
Variants

std::atomic_ref<T>:: atomic_ref

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
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 对象。
如果 obj 未按 required_alignment 对齐,则行为未定义。
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