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::futureobject is not usually created directly- Obtained from an
std::promiseobject - Or returned by an asynchronous operation
- Obtained from an
-
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 completewait_for()andwait_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::futureobject - Sets up the shared state with it
- Creates an associated
-
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::futureobject associated with this promise
- Returns the
-
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::promiseobject
- Created an
-
Producer task function
- Takes the
std::promiseobject as argument - Calls
set_value() - Or
set_exception()
- Takes the
-
Consumer task function
- Takes the associated
std::futureobject as argument - Calls
get() - Or
wait()and friends
- Takes the associated