C++线程池

43

有没有像boost一样的好用的开源线程池C++实现来用于生产代码中呢?

请提供示例代码或使用示例代码的链接。


Boost 有什么问题? - David Rodríguez - dribeas
5
Boost中没有内置的线程池,对吗? - Steve Townsend
@Steve Townsend:好的,抱歉......我记得boost里有一个,但实际上并没有(没有被接受)。可以在http://threadpool.sourceforge.net/index.html中找到一个线程池。 - David Rodríguez - dribeas
这个 FOSS 项目是我尝试创建一个线程池库的努力,如果你想的话可以去看看。-> https://code.google.com/p/threadpool11/ - Etherealone
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的销毁将等待所有线程完成。


2
在语句 pool tp(2); 中,2 的含义是什么? - Arun
@ArunSaha:表示初始线程的数量。我会将其添加到答案中。 - Diego Sevilla
这个线程池库项目可能会给你一些想法。-> https://code.google.com/p/threadpool11/ - Etherealone
@DiegoSevilla,你好,我想知道我们是否可以使用带参数的函数来执行线程池中的任务?谢谢! - Tianyi
@Tianyi 你可能想要使用一个函数对象来实现。请参见这里:https://dev59.com/dHRC5IYBdhLWcg3wROtQ - DarioP

10

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

2
请不要使用auto_ptr!它是不安全的且已被废弃。 - Shivanshu Goyal

3

我相信你可以使用boost::asio中的io_service来模拟一个线程池。您可以控制io_service池中可用的线程数,然后可以通过“post”将任务提交到io_service,由池中的一个线程执行。每个这样的任务必须是一个函数对象(我相信是这样的)。

我现在无法提供示例,但是asio文档中有关io_service池的内容将概述如何实现这一点。


1

0

本文介绍了使用ffead-cpp框架的示例实现,详情请参阅此处。它提供了直接、基于优先级和计划任务的线程池实现。赶紧来看看吧...


0

这个库是基于Boost.Thread构建的。有一个简短的教程,其中包含一些示例代码。如果这不能满足您的需求,您可以将其用作基线。

如果您选择这种方法,请确保您使用的Boost版本>= 1.37。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接