std::promise
and std::future
(C++)
When to use?
This method is generally preferred of over the Condition Variable when we only want the task to be executed once.
How to include
#include <future>
Example
// C++ program to illustrate the use of std::future and
// std::promise in thread synchronization.
#include <iostream>
#include <thread>
using namespace std;
// callable
void EvenNosFind(promise<int>&& EvenPromise, int begin,
int end)
{
int evenNo = 0;
for (int i = begin; i <= end; i++) {
if (i % 2 == 0) {
evenNo += 1;
}
}
EvenPromise.set_value(evenNo);
}
// driver code
int main()
{
int begin = 0, end = 1000;
promise<int> evenNo;
future<int> evenFuture = evenNo.get_future();
cout << "My thread is created !!!" << endl;
thread t1(EvenNosFind, move(evenNo), begin, end);
cout << "Waiting..........." << endl;
// getting the data
cout << "The no. of even numbers are : "
<< evenFuture.get() << endl;
t1.join();
return 0;
}