User Tools

Site Tools


c:c_threads:important_considerations:do_not_join_a_thread_that_has_been_previously_detached

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 <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;
}

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;
}
c/c_threads/important_considerations/do_not_join_a_thread_that_has_been_previously_detached.txt · Last modified: 2021/03/05 09:37 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki