相关疑难解决方法(0)

了解c ++ 11内存防护

我正在尝试理解c ++ 11中的内存防护,我知道有更好的方法可以做到这一点,原子变量等等,但是想知道这种用法是否正确.我意识到这个程序没有做任何有用的事情,我只是想确保fence功能的使用做了我认为他们做的事情.

基本上,该版本确保在围栏之前在此线程中所做的任何更改对于围栏之后的其他线程可见,并且在第二个线程中对变量的任何更改在围栏之后的线程中是否可见?

我的理解是否正确?或者我完全错过了这一点?

#include <iostream>
#include <atomic>
#include <thread>

int a;

void func1()
{
    for(int i = 0; i < 1000000; ++i)
    {
        a = i;
        // Ensure that changes to a to this point are visible to other threads
        atomic_thread_fence(std::memory_order_release);
    }
}

void func2()
{
    for(int i = 0; i < 1000000; ++i)
    {
        // Ensure that this thread's view of a is up to date
        atomic_thread_fence(std::memory_order_acquire);
        std::cout << a;
    }
}

int main()
{
    std::thread t1 …
Run Code Online (Sandbox Code Playgroud)

c++ atomic c++11

32
推荐指数
2
解决办法
2万
查看次数

标签 统计

atomic ×1

c++ ×1

c++11 ×1