carb::tasking::Promise
Defined in carb/tasking/TaskingTypes.h
-
template<class T = void>
class Promise A facility to store a value that is later acquired asynchronously via a Future created via Promise::get_future().
The carb.tasking implementation is very similar to the C++11 std::promise.
A promise has a “shared state” that is shared with the Future that it creates through Promise::get_future().
A promise is a single-use object. The get_future() function may only be called once, and either set_value() or setCanceled() may only be called once.
A promise that is destroyed without ever having called set_value() or setCanceled() is consider a broken promise and automatically calls setCanceled().
There are three specializations of Promise:
Promise<T>: The base specialization, used to communicate objects between tasks/threads.
Promise<T&>: Reference specialization, used to communicate references between tasks/threads.
Promise<void>: Void specialization, used to communicate stateless events between tasks/threads.
The
void
specialization of Promise is slightly different:Promise<void> does not have Promise::setCanceled(); cancellation state cannot be determined.
Public Functions
-
Promise()
Default constructor.
Initializes the shared state.
-
~Promise()
Destructor.
If the shared state has not yet received a value with set_value(), then it is canceled and made Ready similarly to setCanceled().
-
void swap(Promise &other) noexcept
Swaps the shared state with
other's
.- Parameters
other – A Promise to swap shared states with.
-
Future<T> get_future()
Atomically retrieves and clears the Future from this Promise that shares the same state.
A Future::wait() call will wait until the shared state becomes Ready.
Warning
std::terminate()
will be called if this function is called more than once.- Returns
A Future with the same shared state as this Promise.
-
void set_value(const T &value)
Atomically stores the value in the shared state and makes the state Ready.
Warning
Only one call of set_value() or setCanceled() is allowed. Subsequent calls will result in a call to
std::terminate()
.- Parameters
value – The value to atomically set into the shared state.
-
void set_value(T &&value)
Atomically stores the value in the shared state and makes the state Ready.
Warning
Only one call of set_value() or setCanceled() is allowed. Subsequent calls will result in a call to
std::terminate()
.- Parameters
value – The value to atomically set into the shared state.
-
void setCanceled()
Atomically sets the shared state to canceled and makes the state Ready.
This is a broken promise.
Warning
Calling Future::get() will result in a call to
std::terminate()
; Future::isCanceled() will returntrue
.