C/C++ API Reference
Loading...
Searching...
No Matches
pw::async2::Coro< T > Class Template Reference

Overview

template<typename T>
class pw::async2::Coro< T >

An asynchronous coroutine which implements the C++20 coroutine API.

Why coroutines?

Coroutines allow a series of asynchronous operations to be written as straight line code. Rather than manually writing a state machine, users can co_await any pw_async2 future or another coroutine.

Allocation

Pigweed's Coro<T> API supports checked, fallible allocations with pw::Allocator. The first argument to any coroutine function must be a CoroContext&. This allows the coroutine to allocate space for asynchronously-held stack variables using the CoroContext's allocator.

Failure to allocate coroutine "stack" space will result in the Coro<T> returning Status::Invalid().

Creating a coroutine function

To create a coroutine, a function must:

  • Have an annotated return type of Coro<T>, where T is the type that will be returned from within the coroutine.
  • Use co_return <value> rather than return <value> for any return statements. For pw::Status or pw::Result, use PW_CO_TRY and PW_CO_TRY_ASSIGN rather than PW_TRY and PW_TRY_ASSIGN.
  • Accept a CoroContext as its first argument. The CoroContext's allocator is used to allocate storage for coroutine stack variables held across a co_await point.

Using co_await

Inside a coroutine function, co_await <expr> can be used for pw_async2 futures or other coroutines. The result will be a value of type T.

Public Types

using promise_type = ::pw::async2::internal::CoroPromise< T >
 Used by the compiler to create a Coro<T> from a coroutine function.
 
using value_type = T
 The type this coroutine returns from a co_return expression.
 

Public Member Functions

bool ok () const
 

Static Public Member Functions

static Coro Empty ()
 Creates an empty, invalid coroutine object.
 

Friends

template<typename , typename >
class internal::Awaitable
 
template<typename , ReturnValuePolicy >
class CoroTask
 
template<typename , typename E , ReturnValuePolicy >
class FallibleCoroTask
 

Member Function Documentation

◆ ok()

template<typename T >
bool pw::async2::Coro< T >::ok ( ) const
inline

Whether or not this Coro<T> is a valid coroutine.

This will return false if coroutine state allocation failed or if this Coro<T>::Pend method previously returned a Ready value.


The documentation for this class was generated from the following file: