【问题标题】:Boost asio io_service run exception adn restart from multiple threads提升 asio io_service 运行异常并从多个线程重新启动
【发布时间】:2021-10-13 18:45:39
【问题描述】:

我想知道当在多个线程的 io_context 上使用 boost asio 的 run() 函数时,在处理函数中引发异常时会发生什么。我在 io_context 上调用 run 操作的线程函数如下所示:

while(!io->stopped() && *stop == false) {
    try {
        auto cnt = io->run();
    }catch(std::exception &e) {
        
    }

    if(io->stopped()) {
        break;
    }
}

线程数为 1..N。该文档指出,对 run() 的任何后续调用都必须首先调用 restart() ,但是当仍然有任何对 run() 的活动调用时,不得调用 restart() ,我不知道,因为可能仍有线程调用 run ()。

当只有一个 io_context 和多个线程调用 run() 时,解决办法是什么

【问题讨论】:

    标签: c++ boost-asio


    【解决方案1】:

    您是对的,您需要捕获/处理异常。

    您的难题的解决方案非常简单:run() 实际上不应在循环中调用。这种认识很有帮助,因为它让您意识到一旦run(); 退出正常,您总是可以执行break;

    更一般地说,您还可以检查run/poll{*} 成员函数的返回值:如果它返回零,则服务已停止工作。

    【讨论】:

      【解决方案2】:

      run requires a call to restart 正常退出,以便后续对run 的调用不会立即返回。抛出异常不是正常退出,所以可以立即再次调用run

      您的代码可能只是:

      while(true) {
          try {
              auto cnt = io->run();
              break;
          }catch(std::exception &e) {
              
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-02
        • 2012-04-04
        • 1970-01-01
        相关资源
        最近更新 更多