我正在尝试学习 C++ 中的异步编程。在 Python 中,我们有 await
,我们可以用它从那个点恢复函数,但在 C++ 中,future
等待结果并停止下一行代码。如果我们不想得到结果,而是继续执行下一行代码怎么办?我怎样才能做到这一点?
最佳答案
您可以使用 std::future::wait_for
检查任务是否已完成执行,例如:
if (future.wait_for(100ms) == std::future_status::ready) {
// Result is ready.
} else {
// Do something else.
}
Concurrency TS包括 std::future::is_ready
(可能包含在 C++20 中),它是非阻塞的。如果它包含在标准中,用法将类似于:
auto f = std::async(std::launch::async, my_func);
while (!f.is_ready()) {
/* Do other stuff. */
}
auto result = f.get();
/* Do stuff with result. */
或者,并发 TS 还包括 std::future::then
,我认为它可以例如用作:
auto f = std::async(std::launch::async, my_func)
.then([] (auto fut) {
auto result = fut.get();
/* Do stuff when result is ready. */
});
/* Do other stuff before result is ready. */
关于C++ 异步编程,如何不等待 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49338420/