Future & Promises Class

  • A promise object is associated with a future object
  • Together, they create a "shared state"
    • The promise object stores a result in the shared state
    • The future object gets the result from the shared state

std::future

  • Represents a result that is not yet available

  • One of the most important classes in C++ concurrency

    • Works with many different asynchronous objects and operations
    • Not just std::promise
  • An std::future object is not usually created directly

    • Obtained from an std::promise object
    • Or returned by an asynchronous operation
  • Template class defined in <future>

    • The parameter is the type of the data that will be returned
  • get() member function

    • Obtains the result when ready
    • Blocks until the operation is complete
    • Fetches the result and returns it
  • wait() and friends

    • Block but do not return a result
    • wait() blocks until the operation is complete
    • wait_for() and wait_until() block without a timeout

std::promise

  • Template class defined in <future>

    • The parameter is the type of the result
  • Constructor

    • Creates an associated std::future object
    • Sets up the shared state with it
  • get_future() member function

    • Returns the associated future

std::future<int> prom;
std::future fut = prom.get_future();

  • get_future() member function

    • Returns the std::future object associated with this promise
  • set_value()

    • Sets the result to its argument
  • set_exception()

    • Indicates that an exception has occurred
    • This can be stored in the shared state

Producer-Consumer Model

  • Parent thread

    • Created an std::promise object
  • Producer task function

    • Takes the std::promise object as argument
    • Calls set_value()
    • Or set_exception()
  • Consumer task function

    • Takes the associated std::future object as argument
    • Calls get()
    • Or wait() and friends