c++多线程交替打印AB

#include 
#include 
#include 
#include 

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++部分)