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));
        }          
  • 相关阅读:
    Shiro基础
    Nginx+tomcat集群使用redis共享session
    小程序 wepy wx.createAnimation 向右滑动渐入渐出
    小程序util工具
    记错本~~
    小程序BindTap快速连续点击页面跳转多次
    微信小程序页面无法跳转
    CSS:font-family常用字体中英文对照
    git 常用指令
    js 获取数组重复的元素
  • 原文地址:https://www.cnblogs.com/lidabo/p/9263979.html
Copyright © 2011-2022 走看看