从 std::async 返回的 std::future 在超出范围时挂起

2024-01-05

我正在使用以下组合std::async and std::future from C++ 11。我用来对我在代码中执行的某个活动强制执行 time_outmight我尝试连接到服务器时需要一些时间。

代码如下:

#include <future>
#include <chrono>

std::size_t PotentiallyLongRunningActivity() {
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(10000s);
    return 10;
}

bool DoActivity() {

  bool activity_done = false;
  auto my_future_result(std::async(std::launch::async, []() {
      return PotentiallyLongRunningActivity(); //returns size_t
  }));

  std::future_status my_future_status = my_future_result.wait_for(std::chrono::milliseconds(800));
  if (my_future_status == std::future_status::timeout) {
      activity_done = false;
  }
  else if (my_future_status == std::future_status::ready) {
      if (my_future_result.valid() && my_future_result.get() > 0) {
          activity_done = true;
      }
  }

  return activity_done;
  //my_future_result hangs while exiting this method !!!
}

int main(int argc, char *argv[])
{
    DoActivity();
    return 0;
}

大多数情况下一切都很好。在许多情况下,未来已超时并报告已准备就绪。但是,我观察到的奇怪行为是,在某些情况下,UI 会挂起,因为my_future_result当超出范围时挂起。我通过重复致电确认了这一点my_future_result.get()如果在退出方法之前调用,则永远不会返回。

我该如何解决这个问题?有什么办法可以取消、删除或终止std::future ?


您正在退出函数之前std::async任务已完成。在某些情况下,析构函数std::future将阻塞直到任务完成。

http://en.cppreference.com/w/cpp/thread/future/wait_for http://en.cppreference.com/w/cpp/thread/future/wait_for

在文档中wait_for该示例显示了多次调用wait_for超时后,表明超时行为不会取消std::async task.

没有内置支持(我可以发现)允许从外部杀死线程。这是有道理的,因为如果线程以这种方式终止,则无法正确清理线程使用的系统资源的状态。

相反,最好将超时逻辑放在线程本身中,以便它可以自行终止并正确清理。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 std::async 返回的 std::future 在超出范围时挂起 的相关文章

随机推荐