Content:
- Brief introduction of what is future and promise in C++.
- Sample code to implement promise and future in C++.
- Set an exception in promise and retrieve exception through future.
A std::promise allows you to make a promise,
- to configure a value, a notification, or an exception The promise can also delay the provision of that result.
std::future allows for
- asks with the promise about the availability of the value
- Wait for the promise’s notification.
- Take the promise’s value, a notification, or an exception
Example:
#include <thread>
#include <chrono>
#include <iostream>
#include <future>
using namespace std;
//Step 1 : write function
double work_return_result(int value)
{
cout<<"Executing function."<<endl;
return (value + 3.14);
}
int _tmain(int argc, _TCHAR* argv[])
{
//Step 2 : define promise object;
promise objPromoise;
//Step 3 : define lamda function: set_value of promise object
auto lamda_fun = [&](int term)
{
auto result = work_return_result(term);
objPromoise.set_value(result);
};
//Step 4 : invoke lamda
thread t1(lamda_fun, 10);
//Step 5 : get future from promoise object
future<double> objFuture = objPromoise.get_future();
// Step 6 : print future value
cout<<"Return Value from promise: "<< objFuture.get()<<endl;
return 0;
}
Output:
Thread creation: Executing function.
Return Value from promise: 13.14
Exception handling in promise and future:
As we know that the promise can be used to set value, notification and an exception. So let us go through an example where we can set an exception through promise and later that exception can be retrieved from future and handled.
Example:
#include <thread>
#include <chrono>
#include <iostream>
#include <future>
using namespace std;
double work_return_result(int value)
{
cout<<"Thread cretation: Executing function."<<endl;
if(value < 0)
//Step 1 : throw exception
throw runtime_error("Exception is thread function");
else
return value + 3.14;
}
int _tmain(int argc, _TCHAR* argv[])
{
promise objPromoise;
auto lamda_fun = [&](int term){
try
{
auto result = work_return_result(term);
objPromoise.set_value(result);
}
catch(...)
{
//Step 2 : add try and catch for promise to set exception
objPromoise.set_exception(current_exception());
}
};
//Step 4 : invoke lamda
thread t1(lamda_fun, -1);
//Step 5 : get future from promoise object
future<double> objFuture = objPromoise.get_future();
// Step 6 : print future value
try
{
cout<<"Return Value from promise: "<< objFuture.get()<<endl;
}
catch(const exception &e)
{
//Step 3 : add try and catch to future to get exception
cerr<<e.what()<<endl;
}
t1.join();
return 0;
}
Output:
Thread cretation: Executing function.
Exception is thread function