zoukankan      html  css  js  c++  java
  • boost::threadpool 调用类成员变量并传入参数 的方法

    1. 首先到官网下载


    2. 包含头文件

    #include "../boost/threadpool.hpp"



    3. 声明threadpool对象, 

    boost::threadpool::fifo_pool m_poolCmdProcess;

    上面声明了一个FIFO线程池, 即先进先出

    4. 声明一个Runnable适配类 来包装你的类及成员函数

                    class Runnable
                    {
                                    typedef boost::function<void (/*CCommunicationMap*, */ICommandContextEx*)> function;

                    private:
                                    function _f;
                                    CCommunicationMap* _target;
                                    ICommandContextEx* _data;

                    public:
                                    template<class F>
                                    Runnable(CCommunicationMap* target, F f, ICommandContextEx* data)
                                    {
                                                    _f = f;
                                                    _target = target;
                                                    _data = data;
                                    }

                                    ~Runnable(){}

                                    void run()
                                    {
                                                    //_target->TestCommand(_data);
                                                    _f(/*_target, */_data);
                                    }
                    };
      

    上面 function 声明了一个函数模板, 此模板应该和你要关联的类成员函数类型一致。

    5. 调用threadpool的schedule方法 启动线程



                                   boost::function<void (/*CCommunicationMap*, */ICommandContextEx*)>     fun;
                                    fun boost::bind(&CCommunicationMap::TestCommand, &m_communication, _1);

                                    Runnable* run = new Runnable(&m_communication,  fun, pContext);

                                     boost::threadpool::schedule(m_poolCmdProcess, boost::shared_ptr<Runnable>(run));


    注意: 
    threadpool库中的pool_adaptors.hpp头文件有错误, 需要我们改动源码(注释的为原来代码,下面的为改动后的代码), 具体为:
        template<typename Pool, typename Runnable>
        bool schedule(Pool& pool, shared_ptr<Runnable> const & obj)
        {          
                                    //return pool->schedule(bind(&Runnable::run, obj));
                                    return pool.schedule(bind(&Runnable::run, obj));
        }          


  • 相关阅读:
    Python-list
    C3P0数据库连接池使用中的问题
    不变类和可变类
    apollo配置中心部署文档
    Apollo使用文档(Java)
    Redis偶发连接失败案例分析
    创建Kibana耗时报表
    Session服务器配置,如何保存在专门的StateServer服务器中
    Linux命令对应的英文全称
    IIS记录真实来源IP,Advanced Logging(高级日志)的安装以及X-Forwarded-For的配置
  • 原文地址:https://www.cnblogs.com/muzizongheng/p/3169079.html
Copyright © 2011-2022 走看看