aja
aja

Reputation: 97

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

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?

Upvotes: 3

Views: 14989

Answers (2)

Felix Glas
Felix Glas

Reputation: 15524

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?

Upvotes: 10

Vittorio Romeo
Vittorio Romeo

Reputation: 93364

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.

Upvotes: 4

Related Questions