多线程顺序打印ABC

#include <iostream>
#include <thread>
#include <condition_variable>
#include <vector>
#include <algorithm>

using namespace std;

std::mutex my_mutex;
std::condition_variable m_cond;
char g_ch = A;
void printf_(char ch) {
    int cyc = 10;
    for (int i = 0; i < cyc; ++i) {
        std::unique_lock<std::mutex> lk(my_mutex);
        m_cond.wait(lk, [ch] {return ch == g_ch; });
        std::cout << ch << std::endl;
        if (ch == A) {
            g_ch = B;
        }
        else if (ch == B) {
            g_ch = C;
        }
        else {
            g_ch = A;
        }
        lk.unlock();
        m_cond.notify_all();
    }
}

void thread_log_() {

    thread m_thread1(printf_, A);
    thread m_thread2(printf_, B);
    thread m_thread3(printf_, C);
    m_thread1.join();
    m_thread2.join();
    m_thread3.join();
}

 

多线程顺序打印ABC

上一篇:C语言及程序设计进阶例程-24 查找问题及其求解


下一篇:实时流技术来源及比较