In C++ multithreading, a thread is the basic unit that can be executed within a process and to communicate two or more threads with each other, std::promise in conjunction with std::future can be used. In this article, we will discuss the std::promise in C++ and how to use it in our program.
What is std:: promise in C++?
std::promise is a class template that is used with std::future class and it promises to set the value of the std::future object that can be accessed in another thread. The main functionality of this method is to provide a method for one thread to fulfill a promise (set a value or an exception), and another thread to retrieve that value or exception at a later point in time thereby defining the future references.
It is generally helpful in producer-consumer type problems.
How to Use std::promise?
To use std::promise include the <future> header and follow the below steps:
- Create a std::promise Object: Define an object of type promise that will hold the value that will be set in the future.
- Create a std::future Object: Create a future object that will be associated with our promise using the get_future() member function and it will be used to access the value once it's set.
- Set the Value in the std::promise: From a producer thread, call promise by setting the corresponding values with the promise we can set a value using set_value()or set exception thrown using set_exception().
- Retrieving Value from the std::future: Use std::future to get a value from a consumer thread using the get() function of future to get the values associated or get the error associated.
Example of std::future in C++
The below example demonstrates the use of "std::promise" and "std::future" to communicate between threads.
C++
// C++ program to use std::promise and std::future to
// communicate between threads.
#include <future>
#include <iostream>
#include <stdexcept>
#include <thread>
using namespace std;
// Function to perform some computation and set the result
// in a promise
void RetrieveValue(promise<int>& result)
{
try {
int ans = 21095022;
// Set the result in the promise
result.set_value(ans);
}
catch (...) {
// if an error occurs set the exception
result.set_exception(current_exception());
}
}
int main()
{
// Step 1: Creating a std::promise object
promise<int> myPromise;
// Step 2: Associate a std::future with the promise
future<int> myFuture = myPromise.get_future();
// Step 3: Launching a thread to perform computation and
// set the result in the promise
thread computationThread(RetrieveValue, ref(myPromise));
// Step 4: Retrieve the value or handle the exception in
// the original thread
try {
int result = myFuture.get();
cout << "Result: " << result << endl;
}
catch (const exception& e) {
cerr << "Exception is: " << e.what() << endl;
}
// thread finishes
computationThread.join();
return 0;
}
Output
Result: 21095022
Explanation: In the above example, the result is 21095022 because the RetriveValue function sets the value '21095022' in the promise and the main() function calls myFuture.get() to get the corresponding value which will print '21095022' since no error is thrown.
Conclusion
In conclusion, concurrent programming can be done in C++ using "std::promise" in C++. This along with "std::future" is part of the broader C++11/14 concurrency features. This is a useful and simple method that helps in data transfer and also allows us to handle exceptions.
Similar Reads
Promises in NodeJS Promises are a fundamental concept in asynchronous programming in JavaScript, especially in NodeJS, where non-blocking I/O operations are key to performance. Promises allow us to handle asynchronous operations more efficiently than traditional callback functions, leading to cleaner, more readable co
8 min read
Promises in NodeJS Promises are a fundamental concept in asynchronous programming in JavaScript, especially in NodeJS, where non-blocking I/O operations are key to performance. Promises allow us to handle asynchronous operations more efficiently than traditional callback functions, leading to cleaner, more readable co
8 min read
std::shared_mutex in C++ In C++, std::mutex is a mechanism that locks access to the shared resource when some other thread is working on it so that errors such as race conditions can be avoided and threads can be synchronized. But in some cases, several threads need to read the data from shared resources at the same time. H
4 min read
std::function in C++ The std::function() in C++ is a function wrapper class which can store and call any function or a callable object. In this article, we will learn about std::function in C++ and how to use it in different cases.Table of ContentWhat is std::function in C++?Example of std::functionMember Functions of s
5 min read
queue push() and pop() in C++ STL The std::queue::push() and std::queue::pop() functions in C++ STL are used to push the element at the back of the queue and remove the element from the front of the queue respectively. They are the member functions of the std::queue container defined inside the <queue> header file.In this arti
2 min read
Mutex in C++ Mutex stands for Mutual Exclusion. In C++, std::mutex class is a synchronization primitive that is used to protect the shared data from being accessed by multiple threads simultaneously. The shared data can be in the form of variables, data structures, etc. std::mutex class implements mutex in C++.
4 min read