0

I know that the join method blocks the current thread and waits until the task is done. So how is it possible that I can do something like this:

void task()
{
   while(true)
   {
       //do stuff
   }
}

int main()
{
   std::thread t1(task);
   t1.join();
   std::cout << "HELLO" << std::endl;
}

and still see "HELLO" after executing this code. Why does this work?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
U. Iee
  • 27
  • 3

1 Answers1

0

This code should produce an infinite loop.

I cannot reproduce, either on GCC or in Ideone:

enter image description here

However, if you compile with optimization flags on, then the while loop that does nothing may be taken away by the compiler, which explains the behavior. Read more in Optimizing away a "while(1);" in C++0x, provided by Nathan Oliver.

gsamaras
  • 71,951
  • 46
  • 188
  • 305