本文介绍了对通用任务使用boost :: asio线程池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在中发现了一个非常整齐的例子,如何使用boost :: asio创建一个简单的线程池。我基本上想像这样使用它:

In this blog I found a pretty neat example on how to create a simple thread pool using boost::asio. I basically want to use it like this:

#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();
    }
}

Boost :: asio就我所知,主要用于网络IO。但是,我主要想使用它为通用功能。并发问题将使用 asio :: io_service :: strand 来解决。

Boost::asio is, as far as I know, mainly made for network IO. However, I mainly want to use it for general purpose functions. Concurrency issues would be adressed using asio::io_service::strand.

所以我的问题:想创建一个像这样的线程池,即使我的程序不使用网络IO吗?与其他线程池实现相比,是否有任何明显的性能损失?如果是这样,有更好的实现,也是整洁?

So my question: Is it a good idea to create a thread pool like this, even if my program does not use network IO? Are there any obvious performance losses compared to other thread pool implementations? If so, are there better implementations that are also as neat?

推荐答案

Boost.Asio不仅仅用于网络编程,请参阅。它对诸如

Boost.Asio is not solely for network programming, see the reference documentation. It has extensive support for things like


  • 等基于时间的操作( deadline_timer

  • 信号处理

  • 平台特定操作,例如posix流和Windows处理

我已经将它用于其他用途在几个应用程序以及。一个示例是线程池,用于为可能长时间运行的阻塞数据库操作提供服务,同时为应用程序提供异步接口。 Boost.Asio真的是一个非常强大的库。将它用于通用目的的线程池,因为你的建议可以工作很好。

I've used it for other purposes in several applications as well. One example being a thread pool to service potentially long running blocking database operations while providing an asynchronous interface for the application. Boost.Asio really is a very powerful library. Using it for a general purpose thread pool as you propose can work just fine.

这篇关于对通用任务使用boost :: asio线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:46