将boost :: asio线程池用于通用任务

Haa*_*hii 10 c++ multithreading boost-asio threadpool c++11

这个博客中,我找到了一个非常巧妙的例子,说明如何使用boost :: asio创建一个简单的线程池.我基本上想要像这样使用它:

#include <thread>
#include <functional>
#include <boost/asio.hpp>

int main ( int argc, char* argv[] ) {
    asio::io_service io_service;
    asio::io_service::work work(io_service);

    std::vector<std::thread> threadPool;

    for(size_t t = 0; t < std::thread::hardware_concurrency(); t++){
        threadPool.push_back(thread(std::bind(&asio::io_service::run, &io_service)));
    }

    io_service.post(std::bind(an_expensive_calculation, 42));
    io_service.post(std::bind(a_long_running_task, 123));

    //Do some things with the main thread

    io_service.stop();
    for(std::thread& t : threadPool) {
        t.join();
    }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,Boost :: asio主要用于网络IO.但是,我主要想将它用于通用功能.将使用并发问题asio::io_service::strand.

所以我的问题:创建这样的线程池是一个好主意,即使我的程序不使用网络IO?与其他线程池实现相比,是否存在明显的性能损失?如果是这样,那么还有更好的实现吗?

Sam*_*ler 6

Boost.Asio不仅仅用于网络编程,请参阅参考文档.它对像这样的东西有广泛的支持

  • 基于时间的操作(deadline_timer)
  • 信号处理
  • 特定于平台的操作,例如posix流和Windows句柄

我也在几个应用程序中将它用于其他目的.一个示例是线程池,用于为应用程序提供异步接口,同时为可能长时间运行的阻塞数据库操作提供服务.Boost.Asio确实是一个非常强大的库.根据您的建议将它用于通用线程池可以正常工作.