![]() |
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:
Example of std::future in C++The below example demonstrates the use of “std::promise” and “std::future” to communicate between threads. C++
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. ConclusionIn 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. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |