44

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();
    }

}

2 Answers 2

80

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

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

and it should work.

2
  • But it will create a temporary object, call a constructor, do assignment, and then call the destructor. The state may be inconsistent. I tried it and it is working, but I do not know if it will ever work.
    – Squall
    May 19, 2012 at 16:36
  • 24
    It works using move semantics. Nothing will be inconsistent, it works by design. Ownership of the new thread of execution will be transferred from the temporary to the array element, leaving the temporary in the same state as a default-constructed thread object i.e. not referring to any thread of execution, so it can be safely destroyed. May 19, 2012 at 18:09
-5

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;
}
5
  • 1
    @Nevin (Since I can't comment on anyone elses answers) have you tried running your solution through valgrind --tool=helgrind? I'm on GCC 4.5.2 and from the output I'm seeing it looks like doing threads like you're showing actually gets into undefined behavior territory with C++11 threads.
    – Kionmaru
    May 19, 2012 at 10:08
  • 10
    There's no need to use new/delete so much.
    – Luc Danton
    May 19, 2012 at 14:37
  • 1
    Kionmaru, see stackoverflow.com/a/10624266/981959 before using helgrind with std::thread. May 19, 2012 at 18:14
  • 3
    You said try using vectors instead of arrays, when an automatic array as the OP used is superior if the number of elements is known and fixed - as clearly seems to be the case for the OP. Not content with that, you then tried to answer a counter-question that no one asked - If you really want to handle memory allocation yourself and use an array of pointers - for some reason, in the process subverting almost every recommended practice for modern C++ code by using manual new/delete everywhere and ignoring the trend towards value/move semantics. What even is this? Aug 7, 2016 at 18:06
  • 2
    I do not see why people have to bash other peoples suggestions. Yes there are issues with this answer but why not keep the discussion purely technical. "What even is your point?" with a question like "what even is this?" Dec 27, 2019 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.