从可连接线程中销毁线程的对象

时间:2014-07-18 14:51:40

标签: c++ c++11

struct Foo
{
   boost::thread thread_;

   void launchThread()
   {
       boost::thread(boost::bind(&Foo::worker, this));
   }

   void worker()
   {
     ~Foo(); 
   }

   ~Foo()
   {
      if (boost::this_thread::get_id() != thread_.get_id())
        thread_.join();
   }

};

在c ++ 11中,在可连接线程中调用声明该线程的类的析构函数是合法的吗?

EDIT1 ,更现实的例子:

struct Holder
{
   std::unique_ptr<SocketClient> client_;
   void ondisconnected(){client_.release();}
   Holder()
   {
      //create SocketClient and launch the thread
   }
}

struct SocketClient 
{
    boost::thread thread_;

    void launchThread()
    {
       boost::thread(boost::bind(&SocketClient ::worker, this));
    }

    void worker()
    {
        run_ = true;
        while (run_)
        { 
            boost::system::error_code error;

            auto receveidBytesCount = socket_.read_some(boost::asio::buffer(socketBuffer_), error);

            if (error == boost::asio::error::eof)
            {
               disconnected_() // call Holder slot  
               return;          
            }
        }
    }

    ~SocketClient ()
    {
        run_ = false;
        socket_.shutdown(boost::asio::socket_base::shutdown_both);
        socket_.close();

        if (boost::this_thread::get_id() == thread_.get_id())
           thread_.detach();
        else
           thread_.join(); 
    }
};

1 个答案:

答案 0 :(得分:4)

没有。在销毁thread对象之前,必须连接或分离可连接线程。如果从该线程调用,则不会这样做。线程的析构函数将调用terminate(),结束程序。

分离线程是否可接受取决于您是否还要销毁线程访问的对象。这相当于你的线程交互的大规模设计,并且通常无法得到回答。

请注意,显式调用析构函数几乎肯定无效;我假设这只是为了说明在线程上调用析构函数(以更合适的方式)。