#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(std::chrono::seconds(1));
unique_lock<std::mutex> lck(data_mutex) ;
data_var.wait(lck,[]{return flag;});
cout<<"thread: "<< this_thread::get_id() << " printf: " << "A" << endl;
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;
flag = true;
data_var.notify_one();
}
}
int main()
{
thread tA(printA);
thread tB(printB);
tA.join();
tB.join();
return 0;
}
c++多线程交替打印AB
最新推荐文章于 2024-09-14 15:28:42 发布