Similar as with other synchronization techniques, the promise is associated
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.
We would like to set a value, of the type
int, to the
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.
.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
.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
the promise sets the value
42 to the future.
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.
The beginning is the same as in previous examples: the include statements and
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 main function creates a promise and retrieves the future from the
promise. Then, we pass the promise to the
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.
std::promise can directly set a value to the associated
In this article, we learned how to use the