从 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/