C++11条件变量condition_variable的一道案例应用

背景

目标:一个线程不断地对变量增加,当增加到10的时候;另一个线程需要将数据重新置为0,依次循环。
此时可以考虑应用条件变量conditon_variable来解决此问题

分析

代码示例

#include <iostream>
#include <stdio.h>
#include <string>
#include <thread>   //多线程头文件
#include <mutex>
#include <vector>
#include <condition_variable>
using namespace std;

std::mutex mtx_;
std::condition_variable cv_;

int data_ = 0;
void increase(){
    std::unique_lock<mutex> lck(mtx_);
    data_++;
    cout<<"thread 1 data is "<<data_<<endl;
    if (data_>10){
        cv_.notify_all();
    }
}
void clear(){
    std::unique_lock<mutex> lck(mtx_);
    cout<<"thread 2 data is "<<data_<<endl;
    //while(data_<=10){
        cv_.wait(lck,[](){return data_>10;});
    //}
    data_ = 0;
}
void run1(){
    while(1){
        std::this_thread::sleep_for(std::chrono::seconds(1));
        increase();
    }
}
void run2(){
    while(1){
        clear();
    }
}
int main(){
    std::thread th1(run2);
    std::thread th2(run1);
    th1.join();
    th2.join();
    return 0;
}

在这里插入图片描述
在这里插入图片描述

注意点

cv_.wait()里面可以用lamda表达式作为判断条件,也可以将wait函数放在while循环中,来避免虚假唤醒,常用做法是放于while循环中来避免虚假唤醒
在这里插入图片描述

运行结果

可以看出结果稳定输出。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alex1_Code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值