I am writing a server application that spawns a new thread for each client connection. I want to make sure all client threads have exited before the main thread exits. This is because according to answers to the question 'What happens to a detached thread when main() exits?' it is undefined behavior if I return from main()
before all detached threads have terminated.
Simply storing all std::thread
instances in a container and calling std::thread::join()
on all of them before I return from main()
is not an option because I might collect a huge amount of thread handles over time. However, joining threads every now and then is also not an option because std::thread::join()
might block for too long and make my server unable to accept new connections.
Therefore I need some mechanism to either reliably wait for detached threads before I return from main()
or find a way to implement a non-blocking version of std::thread::join
.
There have been plenty of similar questions asked before:
- Timeout for thread.join()
- Check if std::thread is still running [duplicate]
- Check if thread is finished in c++11?
- How to check if thread has finished work in C++11 and above?
- How to check if a std::thread is still running?
Answers there propose to use std::async together with std::future, std::promise, or std::condition_variable. But according to the already mentioned question all these mechanisms do not guarantee that the worker thread has really finished executing.
Are std::promise::set_value_at_thread_exit(), std::notify_all_at_thread_exit and std::packaged_task::make_ready_at_thread_exit really the only solutions?