Detached Threads and the Consequences of Main() Exit
Consider a scenario where a detached thread is launched and continues execution after its controlling std::thread object goes out of scope. The standard's potential silence on the subject has sparked concern: what becomes of a detached thread when the main() function exits?
Undefined Behavior or Defined Effects?
The standard lacks explicit guidelines on this matter. However, the response to the original question provides clarification:
Joining Detached Threads and Signal Handlers
Addressing the second question, the response asserts that detached threads can be joined via the *_at_thread_exit family of functions. These functions enable signaling the completion of a thread's execution while ensuring that all destructors have been invoked.
However, employing condition variables or semaphores alone is insufficient for reliable joining. The standard enforces limitations on code execution during signal handling, excluding the use of condition variables unless explicitly permitted by the implementation.
Consequences for Program Behaviour
In light of these observations, the standard's constraints on thread behavior upon main() exit dictate specific actions for developers:
The above is the detailed content of What Happens to Detached Threads When the `main()` Function Exits?. For more information, please follow other related articles on the PHP Chinese website!