What Happens When Detached Threads Outlive Main()?
In C , threads can be detached using detach(), allowing them to run independently of the std::thread object that initially created them. However, the standard's behavior for detached threads when main() exits remains ambiguous.
Standard Silence and Implied Effects
Neither section 1.10 nor 30.3 of the C 14 draft explicitly defines the fate of detached threads when main() exits. This ambiguity leads to several questions:
The lack of explicit guidelines suggests that running out of main() with detached threads must have defined effects, as stopping the detached threads would essentially render detach() meaningless.
Implied Limitations
While the standard does not explicitly state what happens to detached threads, it does provide some constraints:
Joining Detached Threads
The question of whether detached threads can ever be joined is also addressed in the answer. The answer reveals that detached threads can indeed be joined using the *_at_thread_exit family of functions (notify_all_at_thread_exit(), std::promise::set_value_at_thread_exit(), etc.).
Mitigating Undefined Behavior
To avoid undefined behavior when main() exits with detached threads running, consider the following strategies:
Conclusion
Although the C standard does not explicitly define the behavior of detached threads when main() exits, it provides limitations and implications that suggest defined effects. By adhering to these limitations and using the *_at_thread_exit family of functions, programmers can handle detached threads and avoid undefined behavior.
The above is the detailed content of What Happens to Detached Threads When the `main()` Function Exits in C ?. For more information, please follow other related articles on the PHP Chinese website!