Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop for creating threads and joining with variable number of threads

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:

  • Create variable number of std::threads
  • Variable number of threads c++
  • Array of threads and attempting to pass multiple arguments to function is not working?
  • vector of std::threads
  • Creating N number of threads

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

like image 931
C. Begley Avatar asked Nov 15 '18 23:11

C. Begley


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

like image 102
Christophe Avatar answered Nov 14 '22 21:11

Christophe