std::promise and std::future
In this lesson, we will see how you have full control over the task with std::promise and std::future.
We'll cover the following
Promise and future are a mighty pair. A promise can put a value, an exception, or simply a notification into the shared data channel. One promise can serve many std::shared_future
futures. With C++23, we may get extended futures that are compose-able.
std::promise
std::promise
enables us to set a value, a notification, or an exception. In addition, the promise can provide its result in a delayed fashion.
Method | Description |
---|---|
prom.swap(prom2) and |
Swaps the promises. |
std::swap(prom, prom2) |
|
prom.get_future() |
Returns the future. |
prom.set_value(val) |
Sets the value. |
prom.set_exception(ex) |
Sets the exception. |
prom.set_value_at_thread_exit(val) |
Stores the value and makes it ready if the promise exits. |
prom.set_exception_at_thread_exit(ex) |
Stores the exception and makes it ready if the promise exits. |
If the value or the exception is set by the promise more then once, a std::future_error
exception is thrown.
Get hands-on with 1400+ tech skills courses.