• Boost条件变量condition_variable_any


      Boost条件变量可以用来实现线程同步,它必须与互斥量配合使用。使用条件变量实现生产者消费者的简单例子如下,需要注意的是cond_put.wait(lock)是在等待条件满足。如果条件不满足,则释放锁,将线程置为waiting状态,继续等待;如果条件满足,则重新获取锁,然后结束wait,继续向下执行。

    #include "stdafx.h"
    #include <stack>
    #include <boost/bind/bind.hpp>
    #include <boost/thread.hpp>
    #include <boost/thread/lock_factories.hpp>
    using namespace std;
    class Buffer
    {
    private:
        boost::mutex mu;
    
        boost::condition_variable_any cond_put;
        boost::condition_variable_any cond_get;
        int un_read, capacity;
    
        std::stack<int> m_stk;
        bool isFull()
        {
            return un_read == capacity;
        }
        bool isEmpty()
        {
            return un_read == 0;
        }
    public:
        Buffer(size_t n):un_read(0), capacity(n) {}
    
        void put(int x)
        {
            {
                auto lock = make_unique_lock(mu);
                for (; isFull(); )
                {
                    cout << "Full waiting"<<endl;
                    cond_put.wait(lock);
                }
                m_stk.push(x);
                ++un_read;
            }
            cond_get.notify_one();
        }
    
        void get(int *x)
        {
            {
                auto lock = make_unique_lock(mu);
                for (; isEmpty(); )
                {
                    cout<<"Empty waiting..."<<endl;
                    cond_get.wait(lock);
                }
                --un_read;
                *x = m_stk.top();
                m_stk.pop();
            }
            cond_put.notify_one();
        }
    
    };
    
    Buffer buf(5);
    void Producer(int n)
    {
        for (int i=0; i<n; i++)
        {
            cout<< "Putting "<<i<<endl;
            buf.put(i);
        }
    }
    
    void Consumer(int n)
    {
        int x;
        for (int i=0; i<n; i++)
        {
            buf.get(&x);
            cout<<"Getting "<<x<<endl;
        }
    }
    
    int main()
    {
        boost::thread_group tg;
        tg.create_thread(bind(Producer, 20));
    
        tg.create_thread(bind(Consumer, 10));
        tg.create_thread(bind(Consumer, 10));
    
        tg.join_all();
    
        return 0;
    }

      

  • 相关阅读:
    mklink
    SQL Server 定时清理数据库日志文件
    elementui——elform校验循环对象 前端
    vue3.0 Layput布局,基于断点的隐藏类
    You Raise Me Up
    java 8 stream 的 parallelStream会丢失数据的问题
    记一次分布式事务和可用性的接口协调处理
    最近一个考验sql能力的问题浮现
    关于mysql分组后取某列最大值的进行保留该行的sql操作
    树莓派做微型服务器
  • 原文地址:https://www.cnblogs.com/jiayayao/p/6203665.html
Copyright © 2020-2023  润新知