Using std::async instead of std::thread
suggest changestd::async starts or defers a function and returns a std::future for its
result. It is convenient when a task has a single result or exception to return.
Asynchronously calling a function
#include <future>
#include <iostream>
unsigned int square(unsigned int i){
return i*i;
}
int main() {
auto f = std::async(std::launch::async, square, 8);
std::cout << "square currently running\n"; //do something while square is running
std::cout << "result is " << f.get() << '\n'; //getting the result from square
}
Common Pitfalls
- A temporary future returned by
std::asyncwith thestd::launch::asyncpolicy may block in its destructor until the task finishes. Store the future when tasks should overlap:
std::async(std::launch::async, square, 5);
// The temporary future is destroyed at the semicolon and may wait here.
- Without an explicit policy, the implementation may run the function
asynchronously or defer it until the future is waited on. Use
std::launch::asyncwhen asynchronous execution is required. - Beware of race conditions.
More on async on Futures and Promises
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents