首页 > 编程语言 > 详细

多线程顺序打印ABC

时间:2021-08-25 23:33:33      阅读:17      评论:0      收藏:0      [点我收藏+]
#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

原文:https://www.cnblogs.com/221lin/p/15186853.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!