2010-10-21 174 views
41

什么是C++线程池的优秀开源实现,用于生产代码(类似boost)?C++线程池

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

+0

增强的问题是什么? – 2010-10-21 13:55:40

+5

@David - Boost中没有内置线程池,有吗? – 2010-10-21 13:58:22

+0

@Steve Townsend:对,对不起......我以为我记得有一个提升,但它并没有包括在内(尚未被接受)。在http://threadpool.sourceforge.net/index.html – 2010-10-21 14:17:01

回答

21

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

+1

语句'pool tp(2);'中'2'的含义是什么? – Arun 2010-10-21 17:52:57

+0

@ArunSaha:表示初始线程的数量。我会将其添加到答案中。 – 2010-10-21 18:53:59

+0

这个线程池库项目可能会给出一些想法。 - > https://code.google.com/p/threadpool11/ – Etherealone 2013-05-03 10:28:47

0

This library建立在Boost.Thread上。有一些short tutorial与一些示例代码。如果这不符合你的要求,你可以用它作为基准。

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

3

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

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

0

使用ffead-cpp框架的示例实现描述here。它提供了直接的,基于优先级的以及预定的线程池实现。检查出来...

7

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

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