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

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


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

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

and it should work.


With C++0x / C++11, try using vectors instead of arrays of threads; something like this:

vector<thread> mythreads;int i = 0;for (i = 0; i < 8; i++){   mythreads.push_back(dostuff, withstuff);}auto originalthread = mythreads.begin();//Do other stuff here.while (originalthread != mythreads.end()){   originalthread->join();   originalthread++;}

Edit: If you really want to handle memory allocation yourself and use an array of pointers (i.e. vectors just aren't your thing) then I can't recommend valgrind highly enough. It has memory allocation checkers and thread checkers, etc, etc. Priceless for this kind of thing. In any case, here's an example program using an array of manually allocated threads, and it cleans up after itself (no memory leaks):

#include <iostream>#include <thread>#include <mutex>#include <cstdlib>// globals are bad, ok?std::mutex mymutex;int pfunc(){  int * i = new int;  *i = std::rand() % 10 + 1;  // cout is a stream and threads will jumble together as they actually can  // all output at the same time. So we'll just lock to access a shared  // resource.  std::thread::id * myid = new std::thread::id;  *myid = std::this_thread::get_id();  mymutex.lock();  std::cout << "Hi.\n";  std::cout << "I'm threadID " << *myid << std::endl;  std::cout << "i is " << *i << ".\n";  std::cout << "Bye now.\n";  mymutex.unlock();  // Now we'll sleep in the thread, then return.  sleep(*i);  // clean up after ourselves.  delete i;  delete myid;  return(0);}int main (){  std::thread * threadpointer = new std::thread[4];  // This seed will give us 5, 6, 4, and 8 second sleeps...  std::srand(11);  for (int i = 0; i < 4; i++)    {      threadpointer[i] = std::thread(pfunc);    }  for (int i = 0; i < 4; i++)      // Join will block our main thread, and so the program won't exit until      // everyone comes home.    {      threadpointer[i].join();    }  delete [] threadpointer;}