Promise
The promise is the last synchronization mechanism. We already wrote about the
others, namely std::async
,
std::packaged_task
and
std::condition_variable
.
Similar as with other synchronization techniques, the promise is associated
with a std::future
. std::async
and
std::packaged_task
set a value to the future by returning from a
callable object. But the promise can explicitly set the value to the future. Let’s explain how this works.
Promise
We would like to set a value, of the type int
, to the
future.
Creation
First, the default constructor of the std::promise
creates a promise.
The promise has a template parameter int
, because we would
like to set a value of the type int
to the future.
The future
The .get_future()
member function of the
std::promise
creates a future.
The template parameter of the future is the same as the template parameter of the promise.
Setting the value
The .set_value(...)
member function of the
std::promise
sets the value to the future.
We already know how to obtain the value from the future:
In our example, the answer
is 42
, because
the promise sets the value 42
to the future.
Typical usage
The typical usage of the promise is:
-
creating a promise,
-
retrieving the future from the promise,
-
passing the promise to some other thread,
-
setting a value to the future via the promise,
-
obtaining the value from the future.
Temperature tomorrow re-revisited
We will use the following, already well known, story:
A couple, wife and husband, are going on a picnic tomorrow. The wife would like to know what will be the temperature of the weather. Therefore, she asks her husband to look it up.
We modeled this story with the
std::async
and the
std::packaged_task
. But
in this example, we will use the std::promise
for the
synchronization.
The beginning is the same as in previous examples: the include statements and
make_break
function.
The argument of the temperature(...)
is the
std::promise<int>
. At the end, the function sets the value to
the associated future via .set_value(...)
member function of
the promise.
The main function creates a promise and retrieves the future from the
promise. Then, we pass the promise to the temperature(...)
function which is executed in another thread. The
std::promise
is not copyable, therefore
std::move
moves it to the function.
At the end, the .get()
member function of the future
retrieves the value.
The entire source code is available here. The output of the program is:
This is the third solution of this problem. First one used
std::async
and second one used
std::packaged_task
. Now, we can compare the solutions between
each other and see the semantic differences between them.
Summary
The std::promise
can directly set a value to the associated
std::future
with .set_value()
member
function.
In this article, we learned how to use the std::promise
.
Links: