C++線程池
回答
我認爲它仍然沒有被接受進入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
等待所有線程完成。
語句'pool tp(2);'中'2'的含義是什麼? – Arun 2010-10-21 17:52:57
@ArunSaha:表示初始線程的數量。我會將其添加到答案中。 – 2010-10-21 18:53:59
這個線程池庫項目可能會給出一些想法。 - > https://code.google.com/p/threadpool11/ – Etherealone 2013-05-03 10:28:47
你可能想看看http://threadpool.sourceforge.net/
不難實現自己使用Boost.Threadthread pool。根據任務的不同,您可能希望爲隊列使用lock-free容器,而不是Standard Template Library中的一個。例如,fifo
容器來自lock free
庫。
祝你好運!
This library建立在Boost.Thread上。有一些short tutorial與一些示例代碼。如果這不符合你的要求,你可以用它作爲基準。
如果你走這條路線,確保你的Boost版本> = 1.37。
我相信你可以在boost :: asio中模擬一個帶有io_service的線程池。您可以控制可用於io_service池的線程數,然後您可以將任務「發佈」到io_service,這將由池中的一個線程執行。每個這樣的任務必須是一個仿函數(我相信)。
現在我不能在這裏舉一個例子,但iio_service池上的asio文檔將概述如何完成此操作。
我寫了一個小例子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();
下面是一個使用線程池的簡單隻有頭任務隊列(內置升壓):taskqueue.hpp
的TaskQueue project page包括樣本應用程序演示how to use it:
- 1. C#線程池HttpWebRequests
- 2. C#和線程池
- 3. 線程池在C#
- 4. C++:線程池比單線程慢嗎?
- 5. C#,IAsyncResult和線程池
- 6. C++ 11動態線程池
- 7. 調試線程池在C#
- 8. 線程沒有垃圾收集/線程池線程/ C#/ .net
- 9. 線程池中的線程
- 10. 線程池最大線程
- 11. boost線程池
- 12. Servlet線程池
- 13. Windows線程池
- 14. 線程池:DispatchQueue.main.async
- 15. WinAPI線程池
- 16. Silverlight線程池
- 17. Python線程池
- 18. 線程池stucks
- 19. PHP線程池?
- 20. PHP線程池
- 21. QThread線程池
- 22. Java線程池
- 23. 在``C``線程池中運行'POSIX`線程在``C``線程池中運行`函數指針`
- 24. 多線程 - 新線程vs線程池
- 25. 自定義線程池C#問題
- 26. 沉睡在C#線程池中
- 27. C++中的線程池設計
- 28. 從線程池c更新進度條#
- 29. 線程池實現問題(C#3.0)
- 30. 在c中創建線程池#
增強的問題是什麼? – 2010-10-21 13:55:40
@David - Boost中沒有內置線程池,有嗎? – 2010-10-21 13:58:22
@Steve Townsend:對,對不起......我以爲我記得有一個提升,但它並沒有包括在內(尚未被接受)。在http://threadpool.sourceforge.net/index.html – 2010-10-21 14:17:01