How to test the behavior of std::memory_order_relaxed?

/*********************************************************************************************** 
 *   Project Name     : Null
 *   FilePath         : /tmemorder2.cpp
 *   Author           : Borei
 *   Date             : 2022-08-04 09:01:02
 *   LastEditTime     : 2022-08-04 09:21:46
 *   
 *   Description      : 
 *   
 *=============================================================================================*/

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

std::atomic<bool> x,y;

#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void go() {
  std::unique_lock<std::mutex> lck(mtx);
  std::notify_all_at_thread_exit(cv,std::move(lck));
  ready = true;
}

void fun_1(){
    std::unique_lock<std::mutex> lck(mtx);
    while (!ready) cv.wait(lck);

    x.store(true, std::memory_order_relaxed);
    y.store(true, std::memory_order_relaxed);
}

void fun_2(){
    std::unique_lock<std::mutex> lck(mtx);
    while (!ready) cv.wait(lck);

    while (!y.load(std::memory_order_relaxed));
    if (x.load(std::memory_order_relaxed)) 
        std::cout << "y = true also x = true" << std::endl;
}

int main()
{
    x = false;
    y = false;

    std::thread t1(fun_1);
    std::thread t2(fun_2);

    std::thread(go).detach();   // go!

    t1.join();
    t2.join();

    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值