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?

- 378,754
- 76
- 643
- 1,055

- 97
- 2
- 2
- 9
-
1You need a coroutine/fiber library. – llllllllll Mar 17 '18 at 15:23
-
Unclear. Post a [MCVE] that demonstrates the problem. – Jive Dadson Mar 17 '18 at 15:29
2 Answers
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. */

- 15,065
- 7
- 53
- 82
-
1could you write a demo code using concurrency TS , to show its implementation. – aja Mar 18 '18 at 04:31
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.

- 90,666
- 33
- 258
- 416
-
why dont they just copy paste boost into the C++ standard library, because everytime boost comes up with something good, the C++ standard library comes with a bootleg implementation of the same thing – Jun 29 '21 at 08:38