Once a thread is detached you cannot rejoin it to the main thread at a later stage.
#include <iostream> #include <thread> void ShowMessage() { std::cout << "Hello World" << std::endl; } int main() { std::thread t1(ShowMessage); t1.detach(); //..... 100 lines of code t1.join(); // CRASH !!! return 0; }
Always check if a thread can is joinable before trying to join it to the calling thread.
int main() { thread t1(ShowMessage); t1.detach(); //..... 100 lines of code if (t1.joinable()) { t1.join(); } return 0; }