Search⌘ K

Awaitable Types Revisited

Explore the mechanics of awaitable types in C++ coroutines by examining how the co_await operator interacts with member functions like await_ready, await_suspend, and await_resume. Understand the suspension and resumption behavior of coroutines and discover how to implement and use custom awaitable types to manage asynchronous tasks efficiently.

We'll cover the following...

Introduction

We already talked a bit about awaitable types in the previous chapter. But now we need to get a little bit more specific about what co_await does and what an awaitable type is. The keyword co_await is a unary operator, meaning that it takes a single argument. The argument we pass to co_await needs to fulfill some requirements that we will explore in this section.

When we say co_await in our code, we express that we are waiting for something that may or may not be ready. If it’s not ready, co_await suspends the currently executing coroutine and returns control back to its caller. When the asynchronous task has been completed, it should transfer the control back to the coroutine that is originally waiting for the task to finish. From here on, we will typically refer to the awaiting function as the continuation.

Now consider the following expression:

C++
co_await X{};
...