C++三个线程交替打印

#include 
#include 

using namespace std;

mutex mtx;
condition_variable cond_var;
int g_index;

typedef struct {
    const char *str;
    int index;
} Param;

void fun(void *arg)
{
    Param *param = (Param *)arg;
    while (1) {
        this_thread::sleep_for(chrono::seconds(1));
        unique_lock lck(mtx);
        int index = param->index;
        cond_var.wait(lck, [index] {return index == g_index;});
        cout << param->str << endl;
        g_index = (index + 1) % 3;
        cond_var.notify_all();
    }
}

void main()
{
    Param param0 = { "thread 0", 0 },
        param1 = { "thread 1", 1 },
        param2 = { "thread 2", 2 };
    thread t0(fun, ¶m0),
        t1(fun, ¶m1),
        t2(fun, ¶m2);
    t0.join();
    t1.join();
    t2.join();
}

 运行结果:

C++三个线程交替打印_第1张图片

 

你可能感兴趣的:(C++三个线程交替打印)