Using promises and futures to return values from threads
In the first recipe of this chapter, we discussed how to work with threads. You also learned that thread functions cannot return values, and threads should use other means, such as shared data, to do so; however, for this, synchronization is required. An alternative to communicating a return value or an exception with either the main or another thread is using std::promise
. This recipe will explain how this mechanism works.
Getting ready
The promise
and future
classes used in this recipe are available in the std
namespace in the <future>
header.
How to do it...
To communicate a value from one thread to another through promises and futures, do this:
- Make a promise available to the thread function through a parameter, for example:
void produce_value(std::promise<int>& p) { // simulate long running operation { using namespace std::chrono_literals; std::this_thread:...