c++ - 从不从 std::packaged_task 检索 std::future 的结果是否安全?

标签 c++ c++11 stdthread packaged-task

std::packaged_task 创建一个 std::future 是否安全,它在单独的线程上执行,但并不总是检索其结果?

#include <future>
#include <thread>

class Result {
  Result() {}
  ~Result() {}
};

void foo() {
  std::packaged_task<Result()> task(..);
  auto future = task.get_future();
  std::thread thread(std::move(task), ...);
  thread.detach();
  if (future.wait_for(std::chrono::milliseconds(timeout_ms)) == std::future_status::ready) {
    auto result = future.get();  <--- Task didn't take too long, retrieve future result
    ...
  }
}  <--- Task is taking too long, just abort and never call future.get()

它似乎在 Clang/libc++ 上工作:无论是否 get( ) 最终在 std::future 上被调用,但由于我在 C++ 文档中找不到关于此使用模式的任何内容,我想确保它得到官方支持。

最佳答案

这取决于……您认为对您的程序来说什么是安全的。
对于您显示的上下文,它是安全的:

  • future 在对其执行 get 之前被销毁时,它不会阻塞。如果 future 是使用 std::async 创建的,并且如果您在它被销毁之前没有调用 get ,它会一直阻塞直到结果可用。
    在这里查看更多信息:http://en.cppreference.com/w/cpp/thread/future/~future

these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state.

现在,如果 Result 类持有非拥有内存(无论出于何种原因)或其他需要手动释放的资源怎么办。在这种情况下,您的代码的正确性就会受到质疑。更好的做法是将其分派(dispatch)到某个后台线程以处理缓慢移动的任务。

关于c++ - 从不从 std::packaged_task 检索 std::future 的结果是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37536126/

相关文章:

c++ - 如何使用 fseek() 进入一行的开头

c++ - 套接字 - IPPPROTO_TCP 与。 0

c++ - 从另一个 const std::map 初始化 const std::map 的一部分

c++ - vector v 的 v[0]、v.begin() 和 v.data() 之间有什么区别?

c++ - "unpacking"调用匹配函数指针的元组

c++ - 制作代码 "forwarding referencable"

c++ - 创建共享 packaged_task 接受带转发的参数

c++ - 在优先级最低的核心中运行一个线程

c++ - 为什么我需要显式分离短期变量?

c++ - 如何使用 std::thread?