現在很多語言都內置了線程池實現,但C++中卻沒有。本文列舉一些C++實現的線程池工具。
- Boost.Threadpool
項目首頁:http://threadpool.sourceforge.net
Boost.Threadpool是一個基於Boost、跨平台的C++線程池庫。Boost.Threadpool提供了一個便捷的任務調度異步的途徑。線程池可以定制,動態管理,易於集成到您的軟件項目中。該庫已經在多個商業服務器程序中使用,並沒有任何問題的處理高負荷業務。
使用示例:

#include "threadpool.hpp" void normal_task(); void important_task(); void execute_prioritized() { // Create prioritized thread pool boost::threadpool::prio_pool tp; //scoped_pool<boost::threadpool::prio_pool, 0> tp; // Add some tasks to the pool. tp += boost::threadpool::prio_task_func(5, &normal_task); tp += boost::threadpool::prio_task_func(100, &important_task); tp += boost::threadpool::prio_task_func(7, &normal_task); // Add the some threads to the pool. This will start the execution of the tasks. tp->resize(2); // The tasks are processed according to their priority: // important_task(100), nonrelevant_task(7), nonrelevant_task(5). tp->wait(); // Now all tasks are finished and the pool will be destroyed safely when tp goes out of scope. }
- ffead-cpp
項目首頁:http://code.google.com/p/ffead-cpp。
這是一個雄心勃勃的項目,它旨在將C++帶入Web開發的世界。正像在它的介紹頁面所聲明的那樣:
“該框架是為C++平台上快速發展的企業級應用而開發。 這是一個C++的Web框架,C++應用程序框架,C++的REST框架和C++的soap框架,這些框架都內置其中。 它包含Linux/Windows(通過Cygwin)的實現。它是第一個也是唯一的提供非侵入性的依賴注入、業務驅動的組件邏輯、基於POCO發展的C++應用程序框架。大部分的功能是由配置文件控制。”
- POCO C++ libraries
項目首頁:http://pocoproject.org/。
POCO庫是一個使用現代標准ANSI C++以及C++標准庫實現的框架。該框架近似完美實現(壓縮,數據訪問,SSL,加密,XML,線程,IPC-任何你能想到的在程序開發中的東西,它都包含)。它采用Boost授權許可證,而且似乎有很多的用戶。
- Linux下的一個ThreadPool
項目首頁:http://www.hlnum.org/english/projects/tools/threadpool/index.html。
是一個非常簡單的基於lib_pthread的實現。你可以基於它實現你的代碼,而且很可能會按需進行一些進一步的修改。正如在其主頁的介紹,它是:
“一個基於POSIX線程庫的線程池實現。它實現的池是阻塞的,直到有一個job到來,然后它選擇一個空閑線程,並在其上運行這個job。如果此時沒有可用的空閑線程,該線程池會阻塞直到某一正在運行job的線程結束”。
- Windows下的Thread Pool API
項目首頁:http://msdn.microsoft.com/en-us/library/windows/desktop/ms686766%28v=vs.85%29.aspx。
令人驚訝的是Windows也提供了線程池管理的API,而且還有兩套。一套用在Windows XP中,一套用在Windows Vista中,而現在微軟只更新第二套API。
歡迎留言補充!