用于创建线程并使用可变数量的线程连接的循环



我正在构建一个程序,为了测试目的,该程序可以在C++中创建N个线程。我是C++的相对论新手,到目前为止我的尝试是

//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"的已删除构造函数。我不知道这意味着什么,也不知道如何在中修复

注:
我看过:

  • 创建可变数量的std::线程
  • 可变线程数c++
  • 线程数组并试图将多个参数传递给函数不起作用
  • std::线程的矢量
  • 创建N个线程

但我觉得他们没有回答我的问题。它们中的大多数使用pthreads或不同的构造函数。

您不能复制线程。你需要移动它们,以便将它们放入向量中。此外,您不能在循环中创建临时副本来连接它们:您必须使用引用。

这里是一个工作版本

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();
}

在线演示

最新更新