c++交替打印


#include 
#include 
#include 
#include 
 
std::mutex data_mutex;
std::condition_variable data_var;
bool flag = true;
 
void printA()
{
    while(1)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::unique_lock lck(data_mutex) ;
        data_var.wait(lck,[]{return flag;});
        std::cout<<"thread: "<< std::this_thread::get_id() << "   printf: " << "A" < lck(data_mutex) ;
        data_var.wait(lck,[]{return !flag;});
        std::cout<<"thread: "<< std::this_thread::get_id() << "   printf: " << "B" <

编译 : g++ thread.cpp -o thread -std=c++11 -pthread

你可能感兴趣的:(c++交替打印)