【问题标题】:boost::asio::io_service::run() is not exiting when i call boost::asio::io_serive::stop()boost::asio::io_service::run() 在我调用 boost::asio::io_serive::stop() 时没有退出
【发布时间】:2011-12-27 15:57:31
【问题描述】:

您好,我编写了一个使用异步套接字函数的简单应用程序。我在关闭套接字时遇到了一些问题。

在调用套接字上的async_connect 之前,我使用了 5 秒计时器。在某些情况下,连接没有发生并且计时器到期。当计时器到期时,我将关闭套接字tcp_socket.close()。但问题是当我尝试取消而不是关闭时,我的连接回调处理程序根本没有被 boost::asio::error::operation_aborted 错误调用。接下来的所有异步连接调用都会发生同样的事情。

即使我正在关闭 tcp 套接字并销毁已创建线程上的 client_session 对象 join() 调用没有出现意味着 io_service::run() 仍在运行而不退出...:-( 我不知道为什么会这样……尝试了很多其他方法仍然面临同样的问题。

我不知道是什么问题,我们将不胜感激所有建议和解决方案。

我的真实代码看起来像这样。

class client_session
{ 
   public:
   client_session(boost::asio::io_service& io_service_ )tcp_socekt_(io_service_),
                                                        timer_(io_service_)
   {
   }

   ~client_session()
   {
       tcp_socket_.close();
   }

   void OnTimerExpired(const boost::system::error_code& err)
   {
      if( err ) tcp_socket_.close();
   }

   //Its just for example this will be called from upper layer of my module. giving some information about the server.
   void connect()
   {
        //Here am starting the timer 
        timer_.expires_from_now(boost::posix_time::seconds(2));
        timer_.async_wait(boost::bind(&OutgoingSession::OnTimerExpiry, this,PLACEHLDRS::error));

        .......

        tcp_socket_.async_connect(iterator->endpoint(), boost::bind( &OutgoingSession::handle_connect, this, _1, iterator));

        ......
   }

   void OnConnect(const boost::system::error_code& err)
   {
      //Cancelling the timer 
      timer_.cancel();
      .....
      //Register for write to send the request to server
      ......
   }

   private:
   tcp::socket tcp_socket_;
   deadline_timer timer_;
} 

void main()
{
  boost::asio::io_service tcp_io_service;
  boost::asio::io_service::work tcp_work(tcp_io_service);

  boost::thread* worker = new boost::thread(&boost::asio::io_service::run,&tcp_io_service);

  client_session* csession = new client_session(tcp_io_service);
  csession->connect();

  sleep(10);

  tcp_io_service.stop();

  delete csession;

  worker.join();    //Here it not coming out of join because io_service::run() is not exited yet.
  cout<<"Termination successfull"<<endl;
}

【问题讨论】:

  • 我建议发布一些代码。

标签: sockets tcp boost-asio cancellation


【解决方案1】:

发布的代码似乎有几个不同的问题。我建议从较小的步骤开始,即按照

  • startstop asio 工作线程干净(参见下面的解释)
  • 添加代码启动定时器:正确处理OnTimerExpired,检查错误代码
  • async_connect添加代码:当调用连接处理程序时,cancel计时器并检查错误代码。
  • 添加其他异步操作等

一方面,当你cancel连接处理程序中的计时器时,OnTimerExpired处理程序将被boost::asio::operation_aborted调用,然后你close套接字,这可能不是你想要做的。

此外,您给io_service 工作,但仍然调用stop。通常,如果您给 io_service 工作,您希望通过删除工作来停止执行线程(例如,这可以通过将工作存储在智能指针中并重置它来完成)并让当前启动的异步操作干净地完成。

【讨论】:

  • 谢谢拉尔夫...我遇到了其他地方的问题。但是您在上述帖子中提供的信息对我真的很有用...再次感谢...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多