要求使用两个线程交替打印出内容;
#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex data_mutex;
condition_variable data_var;
bool flag = true;
void printA()
{
while(1)
{
this_thread::sleep_for(chrono::seconds(1));
unique_lock<std::mutex> lck(data_mutex) ;
data_var.wait(lck,[]{return flag;});
//cout<<"thread: "<< this_thread::get_id() << " printf: " << "A" ;
cout << "A ";
flag = false;
data_var.notify_one();
}
}
void printB()
{
while(1)
{
unique_lock<std::mutex> lck(data_mutex) ;
data_var.wait(lck,[]{return !flag;});
//cout<<"thread: "<< this_thread::get_id() << " printf: " << "B" <<endl;
cout <<"B "<<endl;
flag = true;
data_var.notify_one();
}
}
int main()
{
cout <<this_thread::get_id<<endl;
thread tA(printA);
thread tB(printB);
tA.join();
tB.join();
return 0;
}