Ensuring a thread is always joined
suggest changeIf the destructor for a std::thread runs while that thread is still joinable, std::terminate is called. A default-constructed or moved-from thread is not joinable; otherwise join() or detach() must be called first. Using RAII, this is generally simple enough to accomplish:
class thread_joiner
{
public:
thread_joiner(std::thread t)
: t_(std::move(t))
{ }
~thread_joiner()
{
if(t_.joinable()) {
t_.join();
}
}
private:
std::thread t_;
};
This is then used like so:
void perform_work()
{
// Perform some work
}
void t()
{
thread_joiner j{std::thread(perform_work)};
// Do some other calculations while thread is running
} // Thread is automatically joined here
This also provides exception safety; if we had created our thread normally and the work done in t() performing other calculations had thrown an exception, join() would never have been called on our thread and our process would have been terminated. join() itself can throw std::system_error, and because a destructor is implicitly noexcept, that exception still calls std::terminate.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents