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();
}
};
爲什麼你要做一個顯式的析構函數?這沒有任何意義。 –
@ T.C。:添加一個更現實的例子來解釋爲什麼我需要這樣做。 – Guillaume07