使用A线程打印1-52,B线程打印A-Z,要求按照12A34B56C....5152Z的顺序进行交替打印

多线程同步问题,都需要用到监视器,用来监视资源是否可用。C++中使用condition_variable,Java中使用Condition来实现同步。

1. 实现思路

  1. 需要有一个全局变量控制当前该哪个线程访问资源
  2. 调用wait,让出资源使用权
  3. 调用notify,通知线程访问资源

2. C++实现

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

namespace its {

std::mutex mtx; //往输出缓冲区打印内容是临界区,所以不同线程间需要互斥
std::condition_variable cv; //监视输出缓冲区这个资源是否可以被其他线程使用
int index = 1; //用来协调线程

void print_number() {
    std::unique_lock<std::mutex> lck(mtx);
    for (int i = 1; i <= 52; i++) {
        if (index % 3 == 0) { //当打印了两个数字后,需要让字母进程打印
            cv.wait(lck);
        }
        std::cout << i;
        index++;
        cv.notify_all();
    }
}

void print_alphabet() {
    std::unique_lock<std::mutex> lck(mtx);
    for (char i = 'A'; i <= 'Z'; i++) {
        if (index % 3 != 0) { //当打印了一个字母后,需要让数字进程打印
            cv.wait(lck);
        }
        std::cout << i;
        index++;
        cv.notify_all();
    }
}
}

int main() {
    std::thread threads[2];
    threads[0] = std::thread(its::print_number);
    threads[1] = std::thread(its::print_alphabet);

    for (auto &th : threads)
        th.join();
    std::cout << std::endl;
    return 0;
}

3. 参考资料

  1. 关于线程池,看这一篇就够了!
posted @ 2020-02-25 14:02  wengle  阅读(338)  评论(0编辑  收藏  举报