/***********************************************************************************************
* 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;
}
How to test the behavior of std::memory_order_relaxed?
最新推荐文章于 2024-09-16 17:46:36 发布