C ++异步编程,如何不等待未来?

编程入门 行业动态 更新时间:2024-10-27 00:30:26
本文介绍了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 ++异步编程,如何不等待未来?

本文发布于:2023-11-23 10:21:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未来

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!