C ++线程池

什么是一个好的开源的C ++线程池实现在生产代码(类似boost)?

请提供您自己的示例代码或示例代码使用情况的链接。

我认为它仍然不被接受进入Boost,而是一个很好的观点: threadpool 。 使用的一些例子,来自网站:

#include "threadpool.hpp" using namespace boost::threadpool; // Some example tasks void first_task() { ... } void second_task() { ... } void third_task() { ... } void execute_with_threadpool() { // Create a thread pool. pool tp(2); // Add some tasks to the pool. tp.schedule(&first_task); tp.schedule(&second_task); tp.schedule(&third_task); // Leave this function and wait until all tasks are finished. } 

对池的参数“2”表示线程的数量。 在这种情况下, tp的销毁等待所有线程完成。

你可能想看看http://threadpool.sourceforge.net/

使用Boost.Thread自己实现线程池并不难。 根据任务的不同,您可能希望对队列使用无锁容器,而不是使用标准模板库中的一个。 例如,来自无lock free库的fifo容器。

祝你好运!

我在这里写了一个小例子。 基本上你需要做的是实现这段代码:

 asio::io_service io_service; boost::thread_group threads; auto_ptr<asio::io_service::work> work(new asio::io_service::work(io_service)); // Spawn enough worker threads int cores_number = boost::thread::hardware_concurrency(); for (std::size_t i = 0; i < cores_number; ++i){ threads.create_thread(boost::bind(&asio::io_service::run, &io_service)); } // Post the tasks to the io_service for(vector<string>::iterator it=tasks.begin();it!=tasks.end();it++){ io_service.dispatch(/* YOUR operator()() here */); } work.reset(); 

我相信你可以在boost :: asio中模拟一个带有io_service的线程池。 您可以控制可用于io_service池的线程数,然后可以将任务“发布”到io_service,这将由池中的一个线程执行。 每个这样的任务必须是一个仿函数(我相信)。

我现在不能在这里举一个例子,但是io_service池上的asio文档将概述如何完成这个工作。

以下是使用线程池(构build于Boost上)的简单头标题任务队列: taskqueue.hpp

TaskQueue项目页面包含一个示例应用程序,演示如何使用它 :

这个库build立在Boost.Thread上。 有一些示例代码的简短教程 。 如果这没有做到你想要的,你可以用它作为基准。

如果你走这条路线,确保你的Boost版本大于1.37。

这里介绍一个使用ffead-cpp框架的示例实现。 它提供了直接的,基于优先级的以及预定的线程池实现。 一探究竟…