Case Study II: Variations of Futures
Understand the control flow and lifetime management of C++20 coroutines used in futures. Learn to implement eager and lazy futures with thread synchronization, memory management using shared pointers, and running coroutines on separate threads safely. This lesson guides you through practical techniques to handle asynchronous tasks effectively in C++20.
We'll cover the following...
Before I create variations of the future from the section The co_return keyword, we should understand its control flow. Comments make the control flow transparent.
The comments should make the control flow obvious. The call createFuture (line 57) causes the creation of an instance of MyFuture (line 49). Before MyFuture's constructor call (line 8) is completed, the promise promise_type is created, executed, and destroyed (lines 19 - 47). The promise uses in each step of its control flow the awaitable std::suspend_never (lines 35 and 39) and, hence, never pauses. It must be allocated to save the result of the promise for the later fut.get() call (line 58). Furthermore, the used std::shared_ptrs (lines 7 and 20) ensure that the program does not cause a memory leak. As a local, MyFuture goes out of scope in ...