43

什么是 C++ 在生产代码中使用的线程池的良好开源实现(类似于 boost)?

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

4

7 回答 7

22

我认为它仍然没有被 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等待所有线程完成。

于 2010-10-21T13:58:06.710 回答
10

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

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

祝你好运!

于 2010-10-21T13:57:06.963 回答
7

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

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();
于 2012-05-29T13:21:07.663 回答
3

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

我现在不能在这里举一个例子,但是关于 io_service 池的 asio 文档将概述如何做到这一点。

于 2010-10-21T14:49:23.480 回答
1

这是一个使用线程池(基于 Boost 构建)的简单的仅包含标头的任务队列:taskqueue.hpp

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

于 2013-03-14T00:19:32.070 回答
0

这个库建立在 Boost.Thread 之上。有一个带有一些示例代码的简短教程。如果这不符合您的要求,您可以将其用作基线。

如果您走这条路线,请确保您使用的是 Boost 版本 >= 1.37。

于 2010-10-21T13:57:09.850 回答
0

此处描述了使用ffead-cpp框架的示例实现。它提供直接的、基于优先级的以及计划的线程池实现。看看这个...

于 2011-05-28T06:05:09.033 回答