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/