两个线程交替打印26个字母

代码

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;

mutex mtx;
condition_variable cv;
bool flag = true;

void print(char c)
{
    cout << c << endl;
}

void print_first_half()
{
    for (char c = 'a'; c <= 'z'; c += 2)
    {
        unique_lock<mutex> lock(mtx);
        cv.wait(lock, [](){ return flag; });
        print(c);
        flag = false;
        cv.notify_one();
    }
}

void print_second_half()
{
    for (char c = 'b'; c <= 'z'; c += 2)
    {
        unique_lock<mutex> lock(mtx);
        cv.wait(lock, [](){ return !flag; });
        print(c);
        flag = true;
        cv.notify_one();
    }
}

int main()
{
    thread t1(print_first_half);
    thread t2(print_second_half);

    t1.join();
    t2.join();

    return 0;
}
posted @ 2023-03-18 22:58  John_Ran  阅读(26)  评论(0编辑  收藏  举报