【发布时间】:2013-03-23 01:42:49
【问题描述】:
相关问题:
关于 C++11:
- C++11: std::thread pooled?
- Will async(launch::async) in C++11 make thread pools obsolete for avoiding expensive thread creation?
关于 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: workers) {
if (t.joinable()) {
t.join();
}
}
arr[4] = std::min_element(arr, arr+4);
}
return 0;
}
我宁愿每次迭代都将任务发送到我的工作线程,并且只创建一次,而不是每次迭代都创建和加入线程。
【问题讨论】:
-
here 的相关问题和我的回答。
-
考虑过使用 tbb(它是 Intel,但免费和开源,并且完全符合您的要求:您只需提交(递归可分)任务而不用担心线程)?
-
这个 FOSS 项目是我尝试创建一个线程池库,如果你想看看。 -> code.google.com/p/threadpool11
-
使用tbb有什么问题?
标签: c++ multithreading c++11 threadpool stdthread