thread destructors in C++0x vs boost

前端 未结 2 1902
小蘑菇
小蘑菇 2020-12-16 16:02

These days I am reading the pdf Designing MT programs . It explains that the user MUST explicitly call detach() on an object of class std::thread i

2条回答
  •  自闭症患者
    2020-12-16 16:25

    Here's one way to implement RAII threads.

    #include 
    #include 
    
    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(new std::thread(&run), ThreadGuard());
    

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

提交回复
热议问题