C++ multi-thread alternate printing

Multi-thread alternate printing

Use mutex and condition variables to realize the function of alternate printing

#include <iostream>
#include <condition_variable>
#include <mutex>
#include <thread>
std::mutex mtx;
std::condition_variable condition;
int num = 1;
bool stop = false;
void handProcess(int val){
    
    
    while(!stop){
    
    
        std::unique_lock<std::mutex>lock(mtx);
        condition.wait(lock,[val](){
    
    
             return num % 3 == val || num > 100;
        });
        if(num > 100){
    
    
              stop = true;
              condition.notify_all();
        }else{
    
    
            int tmp =  val != 0 ? val : 3;
            printf("线程 %d = %d\n", tmp, num++);
            condition.notify_all();
        }

    }
}
int main(){
    
    
      std::thread mythread1(handProcess,1);
      std::thread mythread2(handProcess,2);
      std::thread mythread3(handProcess,0);
      mythread1.join();
      mythread2.join();
      mythread3.join();
      return 1;
}

Guess you like

Origin blog.csdn.net/qq_44741914/article/details/132102969