title: How to reattach thread or wait for thread completion before exiting
body: <p>I have an application that connects to a socket using the asio library. My main thread calls an <code>open()</code> to the socket implementation where it is then detached from the main thread to continue execution.</p>
  
  <p>When <code>thread::detach()</code> is called, the thread can no longer be joined and thus the caller has no idea when the thread has completed its execution. This results, at least in my application, of an unclean shutdown. Resources aren't deallocated properly and, only sometimes, leads to a crash. Is it possible to rejoin the detached thread? I would like to try and avoid using a condition variable.</p>
  
  <p>Here is my example:</p>
  
  <pre><code>io_socket io = new io_socket();
  
  // The call to thread::detach() is done within io_socket::open()
  io-&gt;open();
  
  // Let some things happen...
  std::this_thread::sleep_for(std::chrono::seconds(20));
  
  // Safely kills all operations and resources before delete
  io-&gt;close();
  
  // A hack solution to allow time for the detached thread to do what it needs to do
  //std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  
  // Crashes if I don't allow the detached thread to safely close
  delete io;
  
  return EXIT_SUCCESS;
  </code></pre>