问题:
Relevant questions :相关问题:
About C++11:关于 C++11:
- C++11: std::thread pooled? C++11:标准::线程池?
- Will async(launch::async) in C++11 make thread pools obsolete for avoiding expensive thread creation? C++11 中的 async(launch::async) 是否会使线程池过时以避免昂贵的线程创建?
About Boost:关于升压:
- C++ boost thread reusing threads C++ boost 线程重用线程
- boost::thread and creating a pool of them! boost::thread 并创建一个池!
How do I get a pool of threads to send tasks to , without creating and deleting them over and over again?如何获得一个线程池以将任务发送到,而无需一遍又一遍地创建和删除它们? This means persistent threads to resynchronize without joining.这意味着持久线程无需加入即可重新同步。
I have code that looks like this:我有如下代码:
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: workers) {
if (t.joinable()) {
t.join();
}
}
arr[4] = std::min_element(arr, arr+4);
}
return 0;
}
Instead of creating and joining threads each iteration, I'd prefer to send tasks to my worker threads each iteration and only create them once.我宁愿每次迭代都将任务发送到我的工作线程,并且只创建一次,而不是每次迭代都创建和加入线程。
解决方案:
参考一: https://en.stackoom.com/question/145z9参考二: https://stackoom.com/question/145z9