Forgetting to join a thread or detach it (make it unjoinable) before the main program terminates, will cause in a program crash.
For example, the t1 thread is not joined to the main thread.
#include <iostream> #include <thread> using namespace std; void HelloWorld() { cout << "Hello World" << endl; } int main() { thread t1(HelloWorld); //t1.join(); // If the thread is not joined to the main thread it will cause a crash. return 0; }
NOTE: Why does it crash ???
There are two ways to fix this depending on your needs.
int main() { thread t1(HelloWorld); t1.join(); // Join t1 to the main thread. return 0; }
int main() { thread t1(HelloWorld); t1.detach(); // Detach t1 from main thread. return 0; }