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(); } }
You can create the array of threads (or list of threads, even) anywhere outside the for loop. Yes, collect them in an array.
Multithreading in C++ C++ 11 did away with all that and gave us std::thread. The thread classes and related functions are defined in the thread header file. std::thread is the thread class that represents a single thread in C++.
Creating Threads You can specify a thread attributes object, or NULL for the default values. The C++ routine that the thread will execute once it is created. A single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void.
Nothing fancy required; just use assignment. Inside your loop, write
myThreads[i] = std::thread(exec, i);
and it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With