花狗

导航

 
#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();
}

 

posted on 2021-08-25 20:34  花狗  阅读(77)  评论(0)    收藏  举报