A more straightforward version of promise and packaged_task can be found in std::async(). This is a simple function, which takes a callable object (function, bind, lambda, and similar) along with any parameters for it, and returns a future object.
The following is a basic example of the async() function:
#include <iostream>
#include <future>
using namespace std;
bool is_prime (int x) {
cout << "Calculating prime...\n";
for (int i = 2; i < x; ++i) {
if (x % i == 0) {
return false;
}
}
return true;
}
int main () {
future<bool> pFuture = std::async (is_prime, 343321);
cout << "Checking whether 343321 is a prime number.\n";
// Wait for future object to be ready.
bool result = pFuture.get();
if (result) {
cout << "Prime found.\n";
}
else {
cout << "No prime found.\n";
}
return 0;
}
The worker function in the preceding code determines whether a provided integer is a prime number or not. As we can see, the resulting code is a lot more simple than with a packaged_task or promise.