Examples of real-life scenarios and solutions
Now that we’ve learned about some new building blocks of creating asynchronous programs, let’s build solutions for some real-life scenarios. In this section, we will learn how to do the following:
- Cancel asynchronous operation
- Return combined results
- Chain asynchronous operations and create a pipeline
- Create a thread-safe single-producer-single-consumer (SPSC) task queue
Canceling asynchronous operations
As we saw earlier, futures offer the ability to check for completion or timeout before waiting for the result. That can be done by checking the std::future_status
object returned by the std::future
, wait_for()
, or wait_until()
function.
By combining futures with mechanisms such as cancellation flags (by means of std::atomic_bool
) or timeouts, we can gracefully terminate long-running tasks if necessary. Timeout cancellation can be implemented by simply using the wait_for()
and wait_until()
functions...