Loop for creating threads and joining with variable number of threads

Viewed 2242

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

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:

But I don't feel they answer my question. Most of them use pthreads or a a different constructor.

1 Answers

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.

Here a working version

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

Online demo

Related