有三个线程,ID 分别为 A,B,C 要求三个线程按顺序循环打印若干次

std::mutex m;
std::condition_variable cond;
int flag = 0;
constexpr int kLoopTimes = 10;
void foo(int id){
    for (int i = 0; i != kLoopTimes; ++i){
        std::unique_lock<std::mutex> lock(m);
        cond.wait (lock, [&]{return flag == id;});
        std::printf("%c", static_cast<char>('A' + flag));
        flag = ((flag + 1) % 3);
        cond.notify_all ();
    }
}

 

posted @ 2015-11-19 19:40  wu_overflow  阅读(396)  评论(0编辑  收藏  举报