Assume I'm starting a std::thread
and then detach()
it, so the thread continues executing even though the std::thread
that once represented it, goes out of scope.
Assume further that the program does not have a reliable protocol for joining the detached thread1, so the detached thread still runs when main()
exits.
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.
1 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.
If running out of main()
with detached threads running is undefined behaviour, then any use of std::thread::detach()
is undefined behaviour unless the main thread never exits2.
Thus, running out of main()
with detached threads running must have defined effects. The question is: where (in the C++ standard, not POSIX, not OS docs, ...) are those effects defined.
2 A detached thread cannot be joined (in the sense of std::thread::join()
). You can wait for results from detached threads (e.g. via a future from std::packaged_task
, or by a counting semaphore or a flag and a condition variable), but that doesn't guarantee that the thread has finished executing. Indeed, unless you put the signalling part into the destructor of the first automatic object of the thread, there will, in general, be code (destructors) that run after 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?
std::exit
or the exit frommain
is sufficient, but not necessary, to satisfy these requirements." (the whole paragraph may be relevant) Also see [support.start.term]/8 (std::exit
is called whenmain
returns) – dyp