• 用std::condition_variable 实现的生产者,消费者同步的例子


    /* std c++ 多线程同步的例子
     * 用std::condition_variable 实现的生产者,消费者同步的例子
     * 当条件满足了,生产者生产出了产品,消费者再消费数据.
     * 消费者要等待,生产者要通知消费者消费.
     * 简单就是美!
     */
    #include
    #include
    #include
    #include
    #include
    using namespace std;
    std::queue q;    //我们把数据存到队列里,当然不用队列也可以的. 顺便演示一下队列用法
    std::mutex mtx;        //condition 的使用总是伴随者mutex 锁定
    std::condition_variable cond;
    void producer() //生产者线程
    {
        for(int data=0;data<10;data++)
        {
            std::unique_lock locker(mtx); //采用unique_lock 锁定mtx
            q.push(data);
            locker.unlock();        //释放锁
            cond.notify_one();  // Notify one waiting thread, if there is one
            std::this_thread::sleep_for(std::chrono::seconds(1)); //chrono 计时,是一个命名空间
        }
    }
    void consumer() //消费者线程,接受到数据9就退出
    {
        int data = 0;
        while (data != 9)
        {
            std::unique_lock locker(mtx); //采用unique_lock 锁定mtx
            while (q.empty())
                cond.wait(locker); // Unlock mtx and wait to be notified
            data = q.back();
            q.pop();
            locker.unlock();
            std::cout << "t2 got a value from t1: " << data << std::endl;
        }
    }
    int main()
    {
        std::thread t1(producer); //创建线程对象t1, 以producer 函数为线程
        std::thread t2(consumer); //创建线程对象t2, 以consumer 函数为线程
        //主线程等待子线程执行完毕
        t1.join();
        t2.join();
        return 0;
    }

     结果:

     ./test_thread_cpp
    t2 got a value from t1: 0
    t2 got a value from t1: 1
    t2 got a value from t1: 2
    t2 got a value from t1: 3
    t2 got a value from t1: 4
    t2 got a value from t1: 5
    t2 got a value from t1: 6
    t2 got a value from t1: 7
    t2 got a value from t1: 8
    t2 got a value from t1: 9

                            

  • 相关阅读:
    软件测试面试题:做好测试计划的关键是什么?
    golang中的unsafe.Pointer,指针,引用
    RT-Thread UART设备
    php实战案例记录(2)生成包含字母和数字但不重复的用户名
    【C++进阶】:红黑树
    CSP2023总结
    2022 9.13 模拟
    【建议收藏】50 道硬核的 Python 面试题!
    Python机器学习实战-特征重要性分析方法(6):XGBoost(附源码和实现效果)
    软件测试工程师规划需要学什么技能?资深测试分析总结......
  • 原文地址:https://blog.csdn.net/hejinjing_tom_com/article/details/128070695