当前位置:网站首页>std::memory_ order_ seq_ CST memory order

std::memory_ order_ seq_ CST memory order

2022-06-27 09:20:00 wangzai6378

One 、 In the case of multiple producers and consumers

#include <thread>
#include <atomic>
#include <cassert>
 
std::atomic<bool> x = {false};
std::atomic<bool> y = {false};
std::atomic<int> z = {0};
 
void write_x()
{
    x.store(true, std::memory_order_seq_cst);
}
 
void write_y()
{
    y.store(true, std::memory_order_seq_cst);
}
 
void read_x_then_y()
{
    while (!x.load(std::memory_order_seq_cst))
        ;
    if (y.load(std::memory_order_seq_cst)) {
        ++z;
    }
}
 
void read_y_then_x()
{
    while (!y.load(std::memory_order_seq_cst))
        ;
    if (x.load(std::memory_order_seq_cst)) {
        ++z;
    }
}
 
int main()
{
    std::thread a(write_x);
    std::thread b(write_y);
    std::thread c(read_x_then_y);
    std::thread d(read_y_then_x);
    a.join(); b.join(); c.join(); d.join();
    assert(z.load() != 0);  // will never happen
}

        Threads a and b producers , Threads c and d Is the consumer . All producers (a and b) Memory sorting occurs ; All consumers (c and d) At the time of consumption , The code is executed in the memory sequence arranged for production . therefore , here c and d Observe a and b when , Or first x Turn into true, then y Turn into true; Or first y Turn into true, Again x Turn into true. In either case at least 1.

原网站

版权声明
本文为[wangzai6378]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270911297163.html