本文介绍了理解 std::atomic 内存屏障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解 C++ 中的内存屏障是如何工作的.例如,我在这种情况下使用 std::atomic :

I want understand how works memory barriers in C++.For example, i am using std::atomic in that case:

#include <iostream>
#include <atomic>

int main()
{
    std::atomic<int> a;
    int n = load();//returns 1 or other value written by other thread
    a.store (n, std::memory_order_release);
}

上面的代码在语义上等于下面的代码吗?

Is that code above semantically equal to that below code?

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<int> a;
    int n = load();
    std::atomic_thread_fence(std::memory_order_release);
    n = 100;//assume assignment is atomic
}

如果我是对的,我能确定所有可以接受内存屏障作为参数的 C++ 函数的行为是相同的吗?

If i am right, can i be sure that behaviour is equal for all C++ functions which can accept memory barriers as argument?

推荐答案

不,但它相当于:

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<int> a;
    int n = load();
    std::atomic_thread_fence(std::memory_order_release);
    a.store (12345, std::memory_order_relaxed);
    n=100;
}

(尽管该值与您在那里所做的不同).栅栏内必须有一个原子存储.检查条件此处在fence-fence同步"或fence-atomic"下同步".尽管您没有对存储 a 设置任何限制,但它会在 memory_order_release 内,n 也是如此.这就是栅栏的作用.

(although the value is different than what you did up there). There must be an atomic store inside the fence. Check the conditions here under "fence-fence synchronization" or "fence-atomic synchronization". Although you're not setting any constrains on storing a, it will be within the memory_order_release, and so will n. That's what a fence does.

这篇关于理解 std::atomic 内存屏障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 16:39