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

标签 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(); 
    }
};

最佳答案

没有。可连接线程必须在 thread 对象被销毁之前连接或分离。如果从该线程调用,这将不执行任何操作。线程的析构函数将调用 terminate(),结束程序。

分离线程是否可以接受取决于您是否还销毁线程访问的对象。这取决于您的线程交互的大规模设计,并且不能真正得到一般性的回答。

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

关于c++ - 从可连接的线程中销毁线程的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24827909/

相关文章:

c++ - 从各种列表中收集条目的迭代器列表

c++ - unique_ptr 实现中可能存在的错误

c++ - 将 float 数组与 int 数组进行比较

c++ - 奇怪的 VS2012 C++ 解析

c++ - 我应该专门化或重载在 `std::swap` 之类的命名空间中定义的模板吗?

c++11 - boost、clang 或 gcc 谁失败了?与 boost::asio 一起使用的 std::chrono 的问题

c++ - 面向对象编程 - 位域私有(private)结构的公共(public)引用

c++ - 为 Variadic 模板函数推导参数失败

c++ - 模板结构的静态常量成员的不同值

c++ - C++中的继承单例