Search code examples
c++multithreadinginitializationmoveobject-lifetime

Using a temporary object to initialise thread


Is it wrong to initialise a thread using temporary thread object which can go out of scope during the thread's execution?

In the program given below, I've tried the 2 methods given below and both of them ran without any error.

#include<thread>
using namespace std;

void consumer()
{
  for(;;)
   {}
}

int main()
{
  thread t[5];

  for(int i=0;i<5;i++)
  {
    /*
      * Method 1
      t[i]=std::thread(consumer);
    */

    /*
     * Method 2
     thread local(consumer);
     t[i]=std::move(local);
    */

     t[i].detach();
   }
   while(1)
    {}
   return 0;
}

Solution

  • Both methods work fine.

    More precisely, operator= performs a move in both cases. So the state of the created thread is kept in t[i] and after the assignment, both the temporary (case 1) or the local (case 2) are set to a default constructed thread that can die when ending the statement (case 1) or exiting the block (case 2).