join() 失败,如果在线程内部调用 io_context.run()

join() fails if io_context.run() is called inside the thread

本文关键字:io 调用 run 内部 context 失败 如果 join 线程      更新时间:2023-10-16

我收到此错误(如果我使用 std::thread,则会出现类似的"避免资源死锁"错误(:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::thread_resource_error> >'
what():  boost thread: trying joining itself: Resource deadlock avoided

这是导致它的的代码。调用 join(( 时会发生异常。

TCPClient::TCPClient(string EOM_delimiter) 
{
EOM_delimiter_ = EOM_delimiter;
socket_ = make_unique<boost::asio::ip::tcp::socket>(io_context_);
io_context_thread_ = make_unique<boost::thread>([this]()
{ 
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> fake_work = boost::asio::make_work_guard(io_context_);
io_context_.run(); 
});
}
bool TCPClient::disconnect()
{
boost::system::error_code ignored_ec;
boost::system::error_code ec;
socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
socket_->close(ignored_ec);
io_context_.stop();
while (!io_context_.stopped()) { continue; }
io_context_thread_->join(); //this is where the error happens
return true;
}

最后,这是调用情况:

TCPClient tcp_client("n");
//sending and receiving work fine in between..
tcp_client.disconnect();

我很困惑,因为我认为这种死锁只会发生在我从线程本身或它调用的处理程序调用 join(( 时。然而,事实并非如此。我注意到如果我不从线程内部运行io_context,join(( 工作正常。

-提升 v1.66

Fudge..我无意中从处理程序调用了 disconnect(( 并因此调用了 join((。新日新开发银行 谢谢你们!