C++两个线程交替打印

#include 
#include 

using namespace std;

mutex mtx;
condition_variable cond_var;
bool flag = true;

void fun1()
{
	while (1) {
		this_thread::sleep_for(chrono::seconds(1));
		unique_lock lck(mtx);
		cond_var.wait(lck, []{return flag;});
		cout << "thread1" << endl;
		flag = false;
		cond_var.notify_one();
	}
}

void fun2()
{
	while (1) {
		unique_lock lck(mtx);
		cond_var.wait(lck, []{return !flag;});
		cout << "thread2" << endl;
		flag = true;
		cond_var.notify_one();
	}
}

void main()
{
	thread t1(fun1);
	thread t2(fun2);
	t1.join();
	t2.join();
}

 

你可能感兴趣的:(C++两个线程交替打印)