C++ Library - <future>



The <future> header in C++ provides a way to handle asynchronous operations, allowing tasks to be run concurrently and results to be retrieved at a later point. this library is part of the broader concurrency, which enables multi-threaded programming with ease.

It is typically used in combination with std::async, which runs a function asynchronously, or with the std::promise, which manually sets the value for a future object. when the value is ready, it can be accessed using the get() function of the future object. The commonly used C++ <future> copying functions are listed below along with their description.

Including <future> Header

To include the <future> header in your C++ program, you can use the following syntax.

#include <future>

Functions of <future> Header

Below is list of all functions from <future> header.

Sr.No Functions & Description
1 operator=

It assigns the shared state.

2 get_future

It returns a future associated with associated with the result.

3 set_value

It sets the result to specific value.

4 set_exception

It sets the result to indicate an exception.

5 set_value_at_thread_exit

It sets the result to specific value while delivering the notification only at thread exit.

6 swap

It swaps two objects.

7 valid

It check for valid shared state.

8 operator()

It calls the stored task.

9 wait

It waits for the result to become available.

Waiting for Future to be Ready

In the following example, we are going to use the wait() to block the main thread until the asynchronous operation is complete.

#include <iostream>
#include <future>
#include <thread>
int a(int x, int y) {
   std::this_thread::sleep_for(std::chrono::seconds(2));
   return x + y;
}
int main() {
   std::future < int > b = std::async (std::launch::async, a, 2, 1);
   b.wait();
   std::cout << "Result : " << b.get() << std::endl;
   return 0;
}

Output

Following is the output of the above code −

Result : 3
Advertisements