C++11:将向量元素作为线程传递给线程函数

Iqr*_*asi 1 c++ multithreading vector c++11

有没有办法将向量的每个元素作为线程传递给函数?我尝试了以下方法并注释了错误。该程序应该接收一行变量(例如 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);
    }

Run Code Online (Sandbox Code Playgroud)

mni*_*tic 5

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

#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;
}
Run Code Online (Sandbox Code Playgroud)