首页 > 两个线程交替打印0到100
头像
一套带走
编辑于 2021-08-09 10:27
+ 关注

两个线程交替打印0到100

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

using namespace std;

int num = 0;
mutex mtx;
condition_variable cv1;

void printA()
{
    while(1)
    {
        unique_lock<mutex> lck(mtx);
        cv1.wait(lck, [](){return (num & 0x01) == 0;});
        if(num > 100)
        {
            cv1.notify_one();
            break;
        }
        cout << "threadA : " << num++ << endl;
        cv1.notify_one();
    }
}

void printB()
{
    while(1)
    {
        unique_lock<mutex> lck(mtx);
        cv1.wait(lck, [](){return (num & 0x01) == 1;});
        if(num > 100)
        {
            num++;
            cv1.notify_one();
            break;
        }
        cout << "threadB : " << num++ << endl;
        cv1.notify_one();
    }
}

int main()
{
    thread t1(printA);
    thread t2(printB);
    t1.join();
    t2.join();
    cout << "all thread zohngzhi " << endl;
    return 0;
}

全部评论

(0) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

热门推荐