Introduction to Promises and Futures
This lesson gives an introduction to std::promise and std::future which are used in C++ for multithreading.
We'll cover the following...
Promise and future are a mighty pair. A promise can put a value, an exception, or simply a notification into the shared data channel. One promise can serve many std::shared_future
futures. With C++20 we may get extended futures that are compose-able.
Here is an introductory example of the usage of std::promise
and std::future
. Both communication endpoints can be moved to separate threads, so the communication takes place between threads.
// promiseFuture.cpp#include <future>#include <iostream>#include <thread>#include <utility>void product(std::promise<int>&& intPromise, int a, int b){intPromise.set_value(a*b);}struct Div{void operator() (std::promise<int>&& intPromise, int a, int b) const {intPromise.set_value(a/b);}};int main(){int a = 20;int b = 10;std::cout << std::endl;// define the promisesstd::promise<int> prodPromise;std::promise<int> divPromise;// get the futuresstd::future<int> prodResult = prodPromise.get_future();std::future<int> divResult = divPromise.get_future();// calculate the result in a separate threadstd::thread prodThread(product, std::move(prodPromise), a, b);Div div;std::thread divThread(div, std::move(divPromise), a, b);// get the resultstd::cout << "20*10 = " << prodResult.get() << std::endl;std::cout << "20/10 = " << divResult.get() << std::endl;prodThread.join();divThread.join();std::cout << std::endl;}
Thread prodThread
(line 36) gets the function product
(lines 8 -10), the prodPromise
(line 32) and the numbers a
and b
. To understand the arguments of prodThread
, you have to look at the signature of the function. prodThread
needs as its first argument a callable; this is the previously mentioned function product
. The function ...