C++ 多线程顺序打印

打印要求:

三个打印线程顺序进行。

线程要求如下:

线程A:打印A

线程B:打印B

线程C:打印C

打印结果:

A
B
C
A
B
C
A
B
C
A
B
C
A
B

法一:需要锁和共享变量

#include 
#include 
#include 

using std::cout;
using std::endl;
using std::thread;
using std::mutex;
using std::condition_variable;
using std::unique_lock;

enum CVFLAG
{
    INIT,
    A_DONE,
    B_DONE,
    C_DONE
};

mutex mtx;
condition_variable cv;
CVFLAG flag = INIT;

void printA()
{
    unique_lock lock(mtx);
    cout << "A" << endl;
    flag = A_DONE;
    cv.notify_all();
}

void printB()
{
    unique_lock lock(mtx);
    cv.wait(lock, [] { return flag == 1; });
    cout << "B" << endl;
    flag = B_DONE;
    cv.notify_all();
}

void printC()
{
    unique_lock lock(mtx);
    cv.wait(lock, [] { return flag == 2; });
    cout << "C" << endl;
    flag = C_DONE;
    cv.notify_all();
}

int main()
{
    int i = 0;
    while (i < 5)
    {
        thread tA(printA);
        thread tB(printB);
        thread tC(printC);
        tA.join();
        tB.join();
        tC.join();
        ++i;
    }
    return 0;
}

法二:简单粗暴,调整join的顺序

#include 
#include 
#include 

using std::cout;
using std::endl;
using std::thread;

void printA()
{
    cout << "A" << endl;
}

void printB()
{
    cout << "B" << endl;
}

void printC()
{
    cout << "C" << endl;
}

int main()
{
    int i = 0;
    while (i < 5)
    {
        thread tA(printA);
        tA.join();
        
        thread tB(printB);
        tB.join();
        
        thread tC(printC);
        tC.join();
        ++i;
    }
    return 0;
}

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