The function template async runs the function f asynchronously (potentially in a separate thread which might be a part of a thread pool) and returns a std::future that will eventually hold the result of that function call.
Code
std::mutex m;
struct X {
void foo(int i, const std::string& str) {
std::lock_guard lk(m);
std::cout << str << ' ' << i << '\n';
}
void bar(const std::string& str) {
std::lock_guard lk(m);
std::cout << str << '\n';
}
};
int main() {
X x;
// Calls (&x)->foo(42, "Hello") with default policy, may print "Hello 42"
// concurrently or defer execution
std::future a1 = std::async(&X::foo, &x, 42, "Hello");
// Calls x.bar("world!") with deferred policy, prints "world!" when a2.get()
// or a2.wait() is called
std::future a2 = std::async(std::launch::deferred, &X::bar, x, "world!");
a2.wait(); //-> or a2.get() // prints "world!"
} // if a1 is not done at this point, destructor of a1 prints "Hello 42" here