Async Function
-
Defined in
<future> -
Higher level abstraction than
std::thread- We can execute a task with
std::async()which runs in the background - This allows to do other work while the task is running
- Alternatively, it can run synchronously in the same thread
- We can execute a task with
-
Similar syntax to
std::thread's constructor- The task function is the first argument
- Followed by the arguments to the task function
Hello, Async!
// The task function
void hello() {
std::cout << "Hello, Async!\n";
}
int main() {
// Call std::async() to perform the task
std::async(hello);
}
std::async with std::future
-
std::async()returns anstd::futureobject- This contains the result of the task
-
We can call
get()on the future- Or
wait()and friends
- Or
-
This can be in a different thread from the call to
std::async()
Returning a Value
// Task which returns a value
int func() { return 42; }
// Call async() and store the returned future object
auto result = std::async(func);
// Do some other work
// Call get() when we are ready
int answer = result.get();
std::async() and Exceptions
- The task may throw an exception
- The exception is stored in the future object
- It will be re-thrown when
get()is called- Similar to using an explicit
std::promise
- Similar to using an explicit
int produce() {
int x = 42;
// Code which may throw an exception
return x;
}
auto result = std::async(produce);
try {
// may throw exception
int x = result.get();
} catch (std::exception& e) {
// Handle the exception
}