std::async
- C++ course
- Advanced
- Lesson 22/83
- 5 min
Learn asynchronous tasks with std::async.
std::async
std::async runs a function on a background thread and returns its result as a std::future. The syntax is auto f = std::async(std::launch::async, func);. func starts on a separate thread; f.get() waits for the result.
std::launch::async starts immediately, std::launch::deferred defers until get is called. The default std::launch::async | std::launch::deferred leaves the choice to the implementation; usually std::launch::async is given explicitly. async is higher level than raw std::thread; it carries return values and propagates exceptions.
Return value
The return type of std::async is std::future<R> where R is the function's return type. For int compute() it returns std::future<int>. The result is read with f.get(); this call blocks until the function finishes.
If the function throws an exception, it is stored in the future and rethrown when get is called. This is a capability that raw std::thread lacks; with thread, a thrown exception calls std::terminate. async is therefore safer for error handling.
Practice async compute
Write int compute() with body return 42;. In main launch it with auto f = std::async(std::launch::async, compute); and print the result with std::cout << f.get();. Include the <future> header.
Starter code
#include <iostream>
#include <future>
// Write the compute function
int main() {
// Launch with async and print the result
return 0;
}Sample solution
#include <iostream>
#include <future>
int compute() {
return 42;
}
int main() {
auto f = std::async(std::launch::async, compute);
std::cout << f.get();
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each expression to its role
| Term | Meaning |
|---|---|
std::async(std::launch::async, func) |
Background launch |
std::launch::async |
Start now |
std::launch::deferred |
Defer |
auto f = ... |
Future result |
2 Complete the async line
auto f = std::____(std::launch::async, compute);
auto f = std::async(std::launch::async, compute);
Explanation: std::async runs the function in the background.
3 What does std::async return?
- std::thread
- std::future Correct answer
- std::function
- std::promise
Explanation: std::async returns the result as a std::future.