When will a thread terminate?

In C++ 11, we can do a simple multi-thread program like:

#include <iostream>
#include <thread>
void hello()
{
std::cout<<"Hello Concurrent World\n";
}
int main()
{
std::thread t(hello);
while(1)
{}
}


In this case, main thread will not end. But for thread t, will it terminate, or I think I can say will it deconstruct after function hello() has been excuted?

If I have another example:

#include <iostream>
#include <thread>
void infinite()
{
while (1)
{
std::cout<<"Hello Concurrent World\n";
}
}
int main()
{
std::thread t(infinite);
}


It is obvious main thread will end soon. If the main thread end, will the thread also end or terminated? Or will it keep running but just we can't see anything?

Thank you.
When you get to the end of your thread function, the thread ends. If the main thread exits while other threads are still running, bad things happen: it causes your program to crash. Always make sure your other threads exit before exiting the main thread.
Thank you very much for reply. You mentioned "If the main thread exits while other threads are still running, bad things happen: it causes your program to crash". Do you mind give little more explanation, why?

Thank you again!
Because in order for the program to end, you'd have to destroy the std::thread objects, and calling the destructor for a thread that hasn't been joined calls std::terminate.

http://en.cppreference.com/w/cpp/thread/thread/~thread

Because the C++ standard says so.
Topic archived. No new replies allowed.