Using std::async instead of std::thread

suggest change

std::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

std::async(std::launch::async, square, 5);
// The temporary future is destroyed at the semicolon and may wait here.

More on async on Futures and Promises

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents