用于创建线程并以可变数量的线程加入的循环 [英] Loop for creating threads and joining with variable number of threads
问题描述
我正在构建一个程序,出于测试目的,该程序可以在C ++中创建N个线程.我是C ++的相对新手,到目前为止,我目前的尝试是
I am building a program that, for testing purposes can create N number of threads in C++. I am relativity new to C++ and my current attempt so far is
//Create a list of threads
std::vector<std::thread> t;
for(i=0; i < THREADS; i ++){
std::thread th = std::thread([](){ workThreadProcess(); });
t.push_back(th);
printf("Thread started \n");
}
for(std::thread th : t){
th.join();
}
我当前遇到一个错误,该错误表明调用了已删除的'std :: thread'构造函数.我不知道这意味着什么或如何修复
I currently an error that says call to deleted constructor of 'std::thread'. I am unusre what this means or how to fix in
注意:
我看过:
Note:
I have looked at:
但是我不觉得他们回答了我的问题.他们大多数使用pthreads或其他构造函数.
But I don't feel they answer my question. Most of them use pthreads or a a different constructor.
推荐答案
您无法复制线程.您需要移动它们才能使其进入向量.同样,您不能在循环中创建临时副本以将它们加入:您必须使用引用.
You can't copy threads. You need to move them in order to get them into the vector. Also, you can't create temporary copies in the loop to join them: you have to use a references instead.
这是一个有效的版本
std::vector<std::thread> t;
for(int i=0; i < THREADS; i ++){
std::thread th = std::thread([](){ workThreadProcess(); });
t.push_back(std::move(th)); //<=== move (after, th doesn't hold it anymore
std::cout<<"Thread started"<<std::endl;
}
for(auto& th : t){ //<=== range-based for uses & reference
th.join();
}
这篇关于用于创建线程并以可变数量的线程加入的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!