====== C - C++ Threads - Important Considerations - Do not join a thread that has been previously detached ======
Once a thread is detached you cannot rejoin it to the main thread at a later stage.
#include
#include
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;
}
----
===== Solution =====
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;
}