thread destructors in C++0x vs boost

Deadly 提交于 2019-11-29 03:41:36

This is indeed true, and this choice is explained in N3225 on a note regarding std::thread destructor :

If joinable() then terminate(), otherwise no effects. [ Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable. —end note ]

Apparently the committee went for the lesser of two evils.


EDIT I just found this interesting paper which explains why the initial wording :

If joinable() then detach(), otherwise no effects.

was changed for the previously quoted one.

Here's one way to implement RAII threads.

#include <memory>
#include <thread>

void run() { /* thread runs here */ }

struct ThreadGuard
{
    operator()(std::thread* thread) const
    {
        if (thread->joinable())
            thread->join(); // this is safe, but it blocks when scoped_thread goes out of scope
        //thread->detach(); // this is unsafe, check twice you know what you are doing
        delete thread;
    }
}

auto scoped_thread = std::unique_ptr<std::thread, ThreadGuard>(new std::thread(&run), ThreadGuard());

If you want to use this to detach a thread, read this first.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!