Using std::async instead of std::thread
suggest changestd::async is also able to make threads. Compared to std::thread it is considered less powerful but easier to use when you just want to run a function asynchronously.
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
std::asyncreturns astd::futurethat holds the return value that will be calculated by the function. When thatfuturegets destroyed it waits until the thread completes, making your code effectively single threaded. This is easily overlooked when you don’t need the return value:
std::async(std::launch::async, square, 5);
//thread already completed at this point, because the returning future got destroyed
std::asyncworks without a launch policy, sostd::async(square, 5);compiles. When you do that the system gets to decide if it wants to create a thread or not. The idea was that the system chooses to make a thread unless it is already running more threads than it can run efficiently. Unfortunately implementations commonly just choose not to create a thread in that situation, ever, so you need to override that behavior withstd::launch::asyncwhich forces the system to create a thread.- 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