C++ 三个线程循环递增输出

//compiler g++ 4.8
#include 
#include 
#include 
#include 

using namespace std;

mutex mt;
condition_variable cv;
int number = 0;
int point = 0;

void func_a(){
    int num = 34;
    while(num--){
        unique_lock<mutex> lk(mt);
        while(number != 0){
            cv.wait(lk);
        }
        point++;
        cout << "A " << point << endl;
        number = 1;
        cv.notify_all();
    }
}
void func_b(){
    int num = 33;
    while(num--){
        unique_lock<mutex> lk(mt);
        while(number != 1){
            cv.wait(lk);
        }
        point++;
        cout << "B " << point << endl;
        number = 2;
        cv.notify_all();
    }
}
void func_c(){
    int num = 33;
    while(num--){
        unique_lock<mutex> lk(mt);
        while(number != 2){
            cv.wait(lk);
        }
        point++;
        cout << "C " << point << endl;
        number = 0;
        cv.notify_all();
    }
}


int main(){
    thread th[3];
    th[0] = thread(func_a);
    th[1] = thread(func_b);
    th[2] = thread(func_c);
    for(int i = 0; i < 3; i++){
        th[i].join();
    }

    return 0;
}

参考博客:
https://www.cnblogs.com/ladawn/p/8671018.html

你可能感兴趣的:(C++,多线程,c++,多线程)