c++ 多线程 条件变量condition_variable(生产者消费者示例)

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

class MesProcess
{
public:
    void Inmsglist()
    {
        for (int i = 0; i < 10; i++)
        {
 
            std::unique_lock<std::mutex> uniqlock(my_mutex);
            std::cout << "Inmsglist线程正在执行,插入数字为:" << i << std::endl;
            msglist.push_back(i);
            my_cond.notify_one();  //尝试把wait和线程唤醒,执行完这里wait就会被唤醒
            //如果添加线程Outmsg_thread2则需要将此处更换为notify_all更稳定
        }
        std::cout<<"in over"<<std::endl;
        in_thread_exit = true;
    }
 
    
    void Outmsglist()
    {
        int command = 0;
        while (true)
        {
            std::unique_lock < std::mutex > uniqlock(my_mutex);
            // my_cond.wait(uniqlock, [this] {           //这里的判断条件为lambda表达式,判断信息队列是否为空,为空返回false,否则返回true
            //     if (!msglist.empty())                 //调用wait函数
            //         return true;
            //     return false;
            // });

            my_cond.wait_for(uniqlock, std::chrono::milliseconds(10),
                [this]{
                if (!msglist.empty())                 //调用wait_for函数
                    return true;
                return false;
                });
            if(in_thread_exit && msglist.empty()){
                std::cout<<"out over"<<std::endl;
                break;
            }
            command = msglist.front();
            msglist.pop_front();
            std::cout << "Outmsglist线程"<<" 正在执行,取出数字为:" << command << std::endl;
            uniqlock.unlock();
            
        }
    }
private:
    std::list<int> msglist;
    std::mutex my_mutex;
    std::condition_variable my_cond;   //生成一个条件变量对象
    bool in_thread_exit = false;
};
 
int main()
{
    // std::cout << "主线程的线程id为: " << std::this_thread::get_id() << std::endl;
 
    MesProcess mpobj;
    std::thread Outmsg_thread(&MesProcess::Outmsglist, &mpobj);
    //std::thread Outmsg_thread2(&MesProcess::Outmsglist, &mpobj);
    std::thread Inmsg_thread(&MesProcess::Inmsglist, &mpobj);
 
    Inmsg_thread.join();
    Outmsg_thread.join();
    //Outmsg_thread2.join();
 
    std::cout << "主线程运行结束" << std::endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值