boost 线程池如何获取任务队列中的任务数量?

待处理任务过多时,想要不再加入新任务或者临时增加线程数量,但是io_service 对象没有能获取任务队列中任务数量的接口?

//g++ test_thread_pool.cpp -g -o test_thread_pool -std=c++11 -lboost_system -lboost_thread
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread/detail/thread_group.hpp>
#include <boost/thread.hpp>

using namespace std;
using namespace boost;


class ThreadPool {
public:
    ThreadPool(int num) : threadNum_(num), stopped_(false), work_(io_) {
        for(int i=i; i<threadNum_; ++i) {
            threads.create_thread(boost::bind(&asio::io_service::run, &io_));
        }
    }   
    ~ThreadPool() {
        stop();  
    }   
    template<typename F, typename...Args>
    void post(F &&f, Args&&...args) {
        io_.post(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
    }   
    void stop() {
        if(!stopped_) {
            io_.stop();    
            threads.join_all();
            stopped_ = true;
        }
    }   

private:
    bool             stopped_;
    boost::thread_group threads;
    int              threadNum_;
    asio::io_service io_;
    asio::io_service::work work_;
};


void test1(int x) {std::cout<<"test 1:"<<x<<std::endl;sleep(4);}
void test2(int y) {std::cout<<"test 2:"<<y<<std::endl;sleep(4);}

int main()
{
    ThreadPool threads(5);

    threads.post([](){std::cout<<"test 1"<<std::endl;});
    threads.post([](){std::cout<<"test 2"<<std::endl;});
    threads.post(test1, 3); 
    threads.post(test2, 5); 
    int temp =0;
    while(1){
        threads.post(test1, temp++); 
        threads.post(test2, temp++);
        sleep(1);
    }
    sleep(10);
    threads.stop();
    while(1){
        // threads.post(test1, temp++); 
        // threads.post(test2, temp++);
        sleep(1);
    }
}
阅读 4.9k
1 个回答

你封装了boost::thread_group,那么可以从接口处解决这个问题:采用一个计数器,在每个任务push进线程池时++计数器;在任务函数外面再包一层函数,这个函数首先调用任务函数,之后--计数器,线程池中执行的都是这个外包函数。这样就可以用计数器来表示当前执行的任务数量了。

另外一个建议:如果想要细致的控制线程池的行为,最好自己实现一个,并不是很难,且不需要依赖boost。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进