c++ - std::memory_order_relaxed 相对于相同原子变量的原子性

标签 c++ multithreading c++11 atomicity memory-barriers

关于内存顺序的 cppreference 文档说

Typical use for relaxed memory ordering is incrementing counters, such as the reference counters of std::shared_ptr, since this only requires atomicity, but not ordering or synchronization (note that decrementing the shared_ptr counters requires acquire-release synchronization with the destructor)



这是否意味着宽松的内存排序实际上不会导致相同变量的原子性?而只是导致与其他宽松的内存负载和/或 compare_exchange 的最终一致性。 ?使用 std::memory_order_seq_cststd::memory_order_relaxed 配对时,将是看到一致结果的唯一方法?

我假设 std::memory_order_relaxed对于同一个变量仍然是原子的,但不提供关于其他数据的加载和存储的任何其他约束。

最佳答案

您问了一些问题,但我将重点关注典型 shared_ptr 使用的排序约束。实现,因为我认为这涵盖了您问题的关键部分。
原子操作对于它所应用的变量(或 POD)总是原子的;对单个变量的修改将以一致的顺序对所有线程可见。
您的问题中描述了轻松原子操作的工作方式:

std::memory_order_relaxed is still atomic with respect to the same variable but does not provide any other constraints about loads and stores with respect to other data


以下是 2 个典型场景,其中可以省略对原子操作的排序约束(即使用 std::memory_order_relaxed):
  • 内存排序不是必需的,因为不依赖于其他操作,或者正如评论者所说,(..) 不是涉及其他内存位置的不变量的一部分。
    一个常见的例子是原子计数器,它由多个线程递增以跟踪特定事件发生的次数。
    如果计数器表示一个不依赖于其他操作的值,则可以放宽增量操作 ( fetch_add )。
    我发现 cppreference 给出的例子不是很有说服力,因为 shared_ptr引用计数确实有依赖性;即一旦其值变为零,内存就会被删除。
    一个更好的例子是 Web 服务器跟踪传入请求的数量,仅用于报告目的。
  • 内存排序是必要的,但是不需要使用排序约束,因为所需的同步已经过去了
    (IMO 这更好地解释了为什么 shared_ptr 的引用计数增量可以放宽,请参见下面的示例)。shared_ptr复制/移动构造函数只能在具有复制/移动自实例的(引用)同步 View 时调用(否则将是未定义的行为)
    因此,无需额外订购。

  • 以下示例说明了 shared_ptr 通常如何使用内存排序。实现修改其引用计数。假设所有线程并行运行
    之后 sp_main已被释放(shared_ptr 引用计数为 10)。
    int main()
    {
        std::vector<std::thread> v;
        auto sp_main = std::make_shared<int>(0);
    
        for (int i = 1; i <= 10; ++i)
        {
            // sp_main is passed by value
            v.push_back(thread{thread_func, sp_main, i});
        }
    
        sp_main.reset();
    
        for (auto &t : v)  t.join();
    }
    
    void thread_func(std::shared_ptr<int> sp, int n)
    {
        // 10 threads are created
    
        if (n == 7)
        {
            // Only thread #7 modifies the integer
            *sp = 42;
        }
    
        // The only thead with a synchronized view of the managed integer is #7
        // All other threads cannot read/write access the integer without causing a race
    
        // 'sp' going out of scope -> destructor called
    }
    
    线程创建保证了 make_shared 之间的(线程间)发生在之前的关系(在 main 中)和 sp的复制/移动构造函数(在每个线程内)。
    因此,shared_ptr的构造函数具有内存的同步 View 并且可以安全地递增 ref_count无需额外订购:
    ctrlblk->ref_count.fetch_add(1, std::memory_order_relaxed);
    
    对于销毁部分,因为只有线程 #7写入共享整数,其他 9 个线程不允许访问相同的内存位置而不会引起竞争。
    这会产生一个问题,因为所有线程大约在同一时间被销毁(假设 reset 中的 main 已经被调用过)
    并且只有一个线程将删除共享整数(将 ref_count 从 1 递减到 0 的那个)。
    最后一个线程在删除整数之前必须具有同步内存 View ,但由于 10 个线程中有 9 个没有同步 View ,因此需要额外排序。
    析构函数可能包含以下内容:
    if (ctrlblk->ref_count.fetch_sub(1, std::memory_order_acq_rel) == 1)
    {
        // delete managed memory
    }
    
    原子 ref_count具有单一的修改顺序,因此所有原子修改都以某种顺序发生。
    假设线程(在本例中)在 ref_count 上执行最后 3 次递减。是线程 #7 (3 → 2), #5 (2 → 1) 和 #3 (1 → 0)。
    线程执行的两个减量 #7#5#3 执行的修改顺序更早.
    发布顺序变为:

    #7 (store release) → #5 (read-modify-write, no ordering required) → #3 (load acquire)


    最终结果是线程#7执行的释放操作已与 #3 执行的获取操作同步并且整数修改(由 #7 )保证具有
    发生在整数销毁之前(由 #3 )。
    从技术上讲,只有访问托管内存位置的线程必须执行释放操作,但由于库实现者不知道线程操作,
    所有线程在销毁时执行释放操作。
    对于共享内存的最终销毁,技术上只有最后一个线程需要执行获取操作,因此 shared_ptr库实现者可以通过设置一个独立的围栏来优化
    仅由最后一个线程调用。
    if (ctrlblk->ref_count.fetch_sub(1, std::memory_order_release) == 1)
    {
        std::atomic_thread_fence(std::memory_order_acquire);
    
        // delete managed memory
    }
    

    关于c++ - std::memory_order_relaxed 相对于相同原子变量的原子性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48124031/

    相关文章:

    c++ - 寻找树中最小值的路径

    c++ - 从argv [1]转换为char * string后,出现什么问题?

    C++11 编译器 : Closest to the standard and how close?

    c# - Parallel.foreach 不处理所有项目

    C++,函数参数中的右值引用

    c++ - "typename"和 "template"关键字 : are they really necessary?

    c++ - 使用带有返回值的 boost::bind 和 boost::thread

    c++ - 尝试在 C++ 中创建简单线程时出错

    c - 如何使 pthreads 池运行任意例程

    c++ - 将 std::function 代理到需要参数数组的 C 函数