C++ future library Intorduction














































C++ future library Intorduction



Introduction Future Library

future is a class template and its object stores the future value,i.e...

std::future object internally stores a value that will be assigned in future and it also provides a mechanism to access that value i.e. using get() member function. 
But if somebody tries to access this associated value of future through get() function before it is available, then get() function will block till value is not available.

The class template std::future provides a mechanism to access the result of asynchronous operations:

  • The creator of the asynchronous operation can then use a variety of methods to query, wait for, or extract a value from the std::future. These methods may block if the asynchronous operation has not yet provided a value.

future objects are only useful when they are valid(description below)Default-constructed future objects are not valid (unless move-assigned a valid future).

A valid future is a future object that is associated to a shared state, and are constructed by calling one of the following functions:
Few Member functions are:

  • constructor        Construct future 
  • destructor         Destroy future 
  • operator=         Move-assign future
  • share                Get shared future 
  • get                   Get value 
  • valid                 Check for valid shared state 
  • wait                  Wait for ready 
  • wait_for            Wait for ready during time span 
  • wait_until          Wait for ready until time point 
EXAMPLE CODE
// 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;
}
OUTPUT

checking, please wait...........
1005444443 is not even



Comments