/***********************************************************************************************
* 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?
最新推荐文章于 2026-06-23 14:07:24 发布
该代码示例展示了在C++中如何使用原子变量和互斥锁及条件变量实现线程间的同步。`go`函数启动了一个新线程,而`fun_1`和`fun_2`函数分别在各自的线程中等待信号并更新原子变量。当条件满足时,`fun_2`会检查并输出相应的变量状态。

239

被折叠的 条评论
为什么被折叠?



