I want to learn how to create multiple threads with the new C++ standard library and store their handles into an array.
How can I start a thread?
The examples that I saw start a thread with the constructor, but if I use array, I cannot call the constructor.
#include <iostream>
#include <thread>
void exec(int n){
std::cout << "thread " << n << std::endl;
}
int main(int argc, char* argv[]){
std::thread myThreads[4];
for (int i=0; i<4; i++){
//myThreads[i].start(exec, i); //?? create, start, run
//new (&myThreads[i]) std::thread(exec, i); //I tried it and it seems to work, but it looks like a bad design or an anti-pattern.
}
for (int i=0; i<4; i++){
myThreads[i].join();
}
}
Nothing fancy required; just use assignment. Inside your loop, write
and it should work.