問題:
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