C++ 11 feature: C++ Multithreading Tutorial: std::promise And std::future

First we shall see some points related to Promise and Future.
Promise:
It is an asynchronous provider.
std:async is another asynchronous provider. That we shall see in next chapter.
Future:
It is an asynchronous return object.
It is used to get a value from promise.
It will wait for notification from promise.
In general:
A “future” allows you to retrieve a value that has been promised to you.

In what situation we are use promise and future?

Suppose we create a thread with a function, and we are waiting for a value. We can do below steps:
1. Create a promise object.
2. Then you create a future object from the promise object.
3. Now when the value is ready, promise object will set the value.
4. Then we can retrieve the value from future object.
Let us understand with the help of an example:
In the below program, we have a function fun(), it will sleep for 5 seconds.
Now we shall set the value for promise object and then get the value form future object.
#include <iostream>       // std::cout
#include <chrono>         // std::chrono::milliseconds
#include <thread>         // std::thread
#include <mutex>          // std::timed_mutex
#include <future>          // std::future

// for more tutorials on C, C++, DS visit www.ProDeveloperTutorial.com

using namespace std;

void fun(std::promise <int> &&PromiseObj)
{
    std::this_thread::sleep_for (std::chrono::seconds(5));
    PromiseObj.set_value(100);
}

int main ()
{
    std::promise<int> PromiseObj;
    std::future<int> FutureObj = PromiseObj.get_future();
    std::thread t1 (fun, std::move(PromiseObj));
    cout<<"Waiting for result"<<endl;
    cout<<"Value form future is "<< FutureObj.get()<<endl;
    cout<<"End"<<endl;
    
    t1.join();
    
  return 0;
}

Output:

Waiting for result
Value form future is 100
End
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *