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));
        }          
  • 相关阅读:
    pgspider sqlite mysql docker 镜像
    pgspider docker 镜像
    pgspider基于pg 的高性能数据可视化sql 集群引擎
    diesel rust orm 框架试用
    golang 条件编译
    Performance Profiling Zeebe
    bazel 学习一 简单java 项目运行
    一个好用node http keeplive agnet
    gox 简单灵活的golang 跨平台编译工具
    mailhog 作为smtp server mock工具
  • 原文地址:https://www.cnblogs.com/lidabo/p/9263979.html
Copyright © 2011-2022 走看看