C++ async programming, how to not wait for future?

≡放荡痞女 提交于 2020-08-26 13:46:48

问题


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?


回答1:


You can use std::future::wait_for to check if the task has completed execution, e.g.:

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

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

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

Also see: How to check if a std::thread is still running?




回答2:


future waits for the results and halts the next line of code

This is only true when you invoke .get() or when the future is being destroyed. You can run multiple tasks in parallel with std::future:

std::future<int> f = std::async(std::launch::async, foo);
auto res0 = bar();
auto res1 = f.get();

In the example above, bar and foo will run in parallel.


If you want to attach asynchronous continuations to an existing future, currently you cannot do that with std::future.

boost::future supports non-blocking .then(...), .when_all(...), and .when_any(...) continuations. These are proposed for standardization in "Extensions for concurrency".

There's also a "Coroutines" TS that aims to introduce resumable functions and co_await/co_yield.

Unsurprisingly, boost also provides a coroutine library that can be used today to implement resumable functions.



来源:https://stackoverflow.com/questions/49338420/c-async-programming-how-to-not-wait-for-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!