user840
user840

Reputation: 162

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

Is there an way to pass each element of a vector as a thread into a function? I tried the following approach and commented out the error. The program is supposed to take in a line of variables(e.g 1 2 3 4 5 6 7) and pass each variable as a thread into the thread function.

I would be very grateful for any help regarding this!

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

Upvotes: 1

Views: 340

Answers (1)

mnistic
mnistic

Reputation: 11020

It sounds like you just want to spawn a thread for each number:

#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;
}

Upvotes: 5

Related Questions