C++11:将矢量元素作为线程传递到线程函数中

C++11: Passing vector elements as threads into thread functions

本文关键字:线程 函数 元素 C++11      更新时间:2023-10-16

有没有办法将向量的每个元素作为线程传递到函数中?我尝试了以下方法并注释掉了错误。 程序应该接受一行变量(例如 1 2 3 4 5 6 7(,并将每个变量作为线程传递到线程函数中。

我将非常感谢有关此的任何帮助!

int main()
{
cout<<"[Main] Please input a list of gene seeds: "<<endl;
int value;
string line;
getline(cin, line);
istringstream iss(line);
while(iss >> value){
inputs.push_back(value);
}

for (int unsigned i = 0; i < inputs.size(); i++) {
//thread inputs.at(i)(threadFunction);
}

听起来你只是想为每个数字生成一个线程:

#include <thread>
void thread_function(int x)
{
std::cout<<"Passed Number = "<<x<<std::endl;
}
int main()  
{
std::vector<std::thread> threads;
...
for (auto i = 0; i < inputs.size(); i++) {
std::thread thread_obj(thread_function, inputs.at(i));
threads.emplace_back(thread_obj);
}
...
for (auto& thread_obj : threads) 
thread_obj.join();
return 0;
}