January 2020
Intermediate to advanced
454 pages
11h 25m
English
In this recipe, we will learn how to manually use a C++ promise and future to provide a function that is executed in parallel with an argument, as well as get the function's return value. To start, let's demonstrate how this is done in its most simplistic form, with the following code:
#include <thread>#include <iostream>#include <future>void foo(std::promise<int> promise){ promise.set_value(42);}int main(void){ std::promise<int> promise; auto future = promise.get_future(); std::thread t{foo, std::move(promise)}; t.join(); std::cout << "The answer is: " << future.get() << '\n'; return 0;}
The preceding example results in the following when executed:
As you can see in the preceding code, the C++ promise is an argument to the ...