The class template std::future
provides a mechanism to access the result of asynchronous operations:
std::future
object to the creator of that asynchronous operation.std::future
. These methods may block if the asynchronous operation has not yet provided a value.// future example
#include <iostream>
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds
// a non-optimized way of checking for even numbers:
bool is_even(int x) {
if (x%2!=0) return false;
return true;
}
int main ()
{
// call function asynchronously:
std::future<bool> fut = std::async (is_even,100544443);
// do something while waiting for function to set future:
std::cout << "checking, please wait";
std::chrono::milliseconds span (100);
while (fut.wait_for(span)==std::future_status::timeout)
std::cout << '.' << std::flush;
bool x = fut.get(); // retrieve return value
std::cout << "\n100544443 " << (x?"is":"is not") << " even.\n";
return 0;
}
checking, please wait........... 1005444443 is not even
Comments