title: What happens to a detached thread when main() exits?
body: <p>Assume I'm starting a <code>std::thread</code> and then <code>detach()</code> it, so the thread continues executing even though the <code>std::thread</code> that once represented it, goes out of scope.</p>
  
  <p>Assume further that the program does not have a reliable protocol for joining the detached thread<sup>1</sup>, so the detached thread still runs when <code>main()</code> exits.</p>
  
  <p>I cannot find anything in the standard (more precisely, in the N3797 C++14 draft), which describes what should happen, neither 1.10 nor 30.3 contain pertinent wording.</p>
  
  <p><sup>1</sup> Another, probably equivalent, question is: "can a detached thread ever be joined again", because whatever protocol you're inventing to join, the signalling part would have to be done while the thread was still running, and the OS scheduler might decide to put the thread to sleep for an hour just after signalling was performed with no way for the receiving end to reliably detect that the thread actually finished.</p>
  
  <p>If running out of <code>main()</code> with detached threads running is undefined behaviour, then <em>any</em> use of <code>std::thread::detach()</code> is undefined behaviour unless the main thread never exits<sup>2</sup>.</p>
  
  <p>Thus, running out of <code>main()</code> with detached threads running must have <em>defined</em> effects. The question is: <em>where</em> (in the <em>C++ standard</em>, not POSIX, not OS docs, ...) are those effects defined.</p>
  
  <p><sup>2</sup> A detached thread cannot be joined (in the sense of <code>std::thread::join()</code>). You <em>can</em> wait for results from detached threads (e.g. via a future from <code>std::packaged_task</code>, or by a counting semaphore or a flag and a condition variable), but that doesn't guarantee that the <em>thread has finished executing</em>. Indeed, unless you put the signalling part into the destructor of the first automatic object of the thread, there <em>will</em>, in general, be code (destructors) that run <em>after</em> the signalling code. If the OS schedules the main thread to consume the result and exit before the detached thread finishes running said destructors, what will^Wis defined to happen?</p>