C ++异步编程,如何不等待未来? [英] C++ async programming, how to not wait for future?

查看:82
本文介绍了C ++异步编程,如何不等待未来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习C ++中的异步编程。在Python中,我们有 await ,可以从那时开始恢复功能,但是在C ++中,未来等待结果,并停止下一行代码。如果我们不想得到结果,而是继续下一行代码怎么办?我怎样才能做到这一点?

I'm trying to learn async programming in C++. In Python, we have await, with which we can resume a function from that point, but in C++ future waits for the results and halts the next line of code. What if we don't want to get the result, but instead continue to the next line of code? How can I do this?

推荐答案

您可以使用 std :: future :: wait_for 来检查任务是否已完成执行,例如 eg

if (future.wait_for(100ms) == std::future_status::ready) {
    // Result is ready.
} else {
    // Do something else.
}

并发TS 包括 std :: future :: is_ready (可能包含在C ++ 20中),这是非阻塞的。如果它包含在标准中,用法将类似于:

The Concurrency TS includes std::future::is_ready (may be included in C++20), which is non blocking. If it gets included in the standard, usage will be something like:

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 ,我认为这可以将 eg 用作:

Alternatively, the Concurrency TS also includes std::future::then, which I interpret can be used e.g. as:

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. */

另请参见:如何检查std :: thread是否仍在运行?

这篇关于C ++异步编程,如何不等待未来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆