2

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;
}
Christophe
  • 68,716
  • 7
  • 72
  • 138
Vishal Sharma
  • 1,670
  • 20
  • 55
  • 2
    Both of the methods in the comments are fine. The thread objects will be stored in the `t` array, and that doesn't go out of scope until the `main` function itself returns. – Some programmer dude Mar 14 '19 at 07:31

1 Answers1

2

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

Christophe
  • 68,716
  • 7
  • 72
  • 138