2010-10-21 201 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();