- Examples
In this lesson, we will look into the use of std::promise and std::future in the scope of concurrency in C++.
We'll cover the following...
Example 1
Press + to interact
// 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 separat 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;}
Explanation
-
Thread
prodThread
(line 36) gets the functionproduct
(lines 8 -10), theprodPromise
(line 32,) and the numbersa
andb
. -
To ...
Access this course and 1400+ top-rated courses and projects.