Introduction to Promises and Futures
Explore the fundamentals of promises and futures in C++ to understand how they facilitate communication between threads. This lesson covers std::promise and std::future usage, setting values and exceptions, waiting for results, and the one-to-many relationship in std::shared_future, preparing you to handle asynchronous operations effectively.
We'll cover the following...
Promise and future make a mighty pair. A promise can put a value, an exception, or simply a notification into the shared data channel. One promise can serve many std::shared_future futures. With C++20, we may get extended futures that are composable.
Here is an introductory example of the usage of std::promise and std::future. Both communication endpoints can be moved to separate threads, so the communication takes place between threads.
Thread prodThread (line 36) gets the function product (lines 8 -10), the prodPromise (line 32) and the numbers a and b. To understand the arguments of prodThread, we have to look at the signature of the function. prodThread needs, as its first argument, a callable; this is the previously mentioned function product. The function product requires a promise of the kind ...