Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of thread objects in C++11?

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();     }  } 
like image 752
Squall Avatar asked May 19 '12 02:05

Squall


People also ask

Can you make an array of threads?

You can create the array of threads (or list of threads, even) anywhere outside the for loop. Yes, collect them in an array.

What is multithreading C ++ 11?

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++.

How do I create multiple threads in CPP?

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.


1 Answers

Nothing fancy required; just use assignment. Inside your loop, write

myThreads[i] = std::thread(exec, i); 

and it should work.

like image 60
Nevin Avatar answered Oct 01 '22 10:10

Nevin