相关问题:
关于C++ 11:
关于Boost:
我如何获得一个线程池,以任务发送到,而无需创建和删除它们一遍又一遍?这意味着要在不加入的情况下重新同步的持久线程.
我的代码看起来像这样:
namespace {
std::vector<std::thread> workers;
int total = 4;
int arr[4] = {0};
void each_thread_does(int i) {
arr[i] += 2;
}
}
int main(int argc, char *argv[]) {
for (int i = 0; i < 8; ++i) { // for 8 iterations,
for (int j = 0; j < 4; ++j) {
workers.push_back(std::thread(each_thread_does, j));
}
for (std::thread &t: …Run Code Online (Sandbox Code Playgroud) 在这个博客中,我找到了一个非常巧妙的例子,说明如何使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,Boost :: asio主要用于网络IO.但是,我主要想将它用于通用功能.将使用并发问题asio::io_service::strand.
所以我的问题:创建这样的线程池是一个好主意,即使我的程序不使用网络IO?与其他线程池实现相比,是否存在明显的性能损失?如果是这样,那么还有更好的实现吗?