このブログでは、boost::asioを使用して単純なスレッドプールを作成する方法についての非常に優れた例を見つけました。私は基本的に次のように使用したいと思います:
#include <thread>
#include <functional>
#include <boost/asio.hpp>
int main ( int argc, char* argv[] ) {
asio::io_service io_service;
asio::io_service::work work(io_service);
std::vector<std::thread> threadPool;
for(size_t t = 0; t < std::thread::hardware_concurrency(); t++){
threadPool.push_back(thread(std::bind(&asio::io_service::run, &io_service)));
}
io_service.post(std::bind(an_expensive_calculation, 42));
io_service.post(std::bind(a_long_running_task, 123));
//Do some things with the main thread
io_service.stop();
for(std::thread& t : threadPool) {
t.join();
}
}
Boost :: asioは、私が知る限り、主にネットワークIO用に作られています。ただし、主に汎用機能に使用したいと思います。並行性の問題は、を使用して解決されasio::io_service::strand
ます。
だから私の質問:私のプログラムがネットワークIOを使用していない場合でも、このようなスレッドプールを作成するのは良い考えですか?他のスレッドプールの実装と比較して、明らかなパフォーマンスの低下はありますか?もしそうなら、同様にきちんとしたより良い実装はありますか?