Coroutine primitives and combinators.

Namespaces

Name

Description

ext

Tools for library authors who are building new co_cleanup types.

Namespace Aliases

Name

Description

impl

Alias for the standard namespace providing coroutine support.

Types

Name

Description

AsyncGenerator

The AsyncGenerator class represents a sequence of asynchronously produced values where the values are produced by a coroutine.

AsyncObject

Base class for objects whose lifetime is managed by an async_closure.

AsyncObjectNonSlotPtr

Owning pointer to an AsyncObject that does not live in a scope slot.

AsyncObjectTag

Tag type identifying an async object owned by an async_closure.

AsyncPipe

An AsyncGenerator with a write end

AsyncScope

Starts and later joins a dynamic, unbounded set of concurrent tasks.

AsyncScopeSlotObject

An AsyncObject stored in a slot of an async scope.

AsyncStackTraceAwaitable

Awaitable that yields the current async stack trace.

AutoCleanup

The user can use AutoCleanup to wrap arguments passed to a CleanableAsyncGenerator. When the coroutine promise of CleanableAsyncGenerator is created it will automatically attach co_scope_exit task that performs async cleanup for all the arguments wrapped in AutoCleanup. This allows to ensure cleanup of the arguments even when next() of the CleanableAsyncGenerator is never co_awaited.

BackgroundTask

A task that runs detached in the background; forward‐declared here.

Baton

A baton is a synchronisation primitive for coroutines that allows a coroutine to co_await the baton and suspend until the baton is posted by some thread via a call to .post().

BoundedAsyncPipe

Bounded variant of AsyncPipe which buffers a fixed number of writes before blocking new attempts to write until the buffer is drained.

BoundedQueue

A coroutine version of bounded queue with given capacity. Both enqueue and dequeue are async awaitable.

CancellableAsyncScope

A cancellable version of AsyncScope. Work added to this scope will be provided a cancellation token for cancelling during join.

ConnectCallback

Handles the connect operation for an AsyncSocketTransport.

ExtendedCoroutineHandle

Extended coroutine_handle<void> assuming the handle is a pointer.

ExtendedCoroutinePromiseCrtp

CRTP base letting a promise expose a more efficient error‐resumption path.

Future

The awaitable read side of a promise/future contract.

Generator

A synchronous coroutine generator that lazily yields a sequence of values.

Mutex

A mutex that can be locked asynchronously using 'co_await'.

PollFuture

A Rust‐style pollable adaptor over a Task or SemiFuture.

PollStream

A Rust‐style pollable adaptor over an AsyncGenerator stream.

Promise

The write side of a promise/future contract used to fulfill a Future.

ReadCallback

Handles data reads for an AsyncTransport.

SerialQueueRunner

SerialQueueRunner

ServerSocket

A coroutine server socket that accepts connections on the same event base as the underlying socket itself.

SharedLock

This type mirrors the interface of std::shared_lock as much as possible.

SharedMutexFair

The folly::coro::SharedMutexFair class provides a thread synchronisation primitive that allows a coroutine to asynchronously acquire a lock on the mutex.

SharedPromise

SharedPromise is a simple wrapper around folly::coro::Promise and folly::coro::Future that allows for fetching cancellable and awaitable futures from a single promise.

SmallUnboundedQueue

Low‐memory unbounded multi‐producer/consumer queue with lower throughput.

StackAwareViaIfAsyncAwaitable

Async‐stack‐aware awaitable that reschedules onto an executor.

StackAwareViaIfAsyncAwaiter

Async‐stack‐aware awaiter that reschedules its inner awaiter onto an executor.

Synchronized

This class is an adaptation of the folly::Synchronized class but is designed to work with coro‐compatible mutexes like coro::SharedMutexFair instead.

Task

Represents an allocated, but not‐started coroutine, which is not yet been bound to an executor.

TaskWithExecutor

Represents an allocated but not yet started coroutine that has already been bound to an executor.

TaskWithExecutorWrapperCrtp

CRTP base implementing the shared behavior of task‐with‐executor wrappers.

TaskWrapperCrtp

CRTP base implementing the shared behavior of task wrappers.

Transport

Coroutine transport backed by an AsyncTransport socket.

TransportCallbackBase

Common base for all transport callbacks.

TransportIf

Abstract interface for a coroutine‐based socket transport.

UnboundedQueue

Wrapper around folly::UnboundedQueue that supports async dequeue.

UpgradeLock

An upgradable lock guard held over a coroutine‐aware mutex.

ViaIfAsyncAwaitable

Awaitable that reschedules its inner awaitable onto an executor.

ViaIfAsyncAwaiter

Awaiter that reschedules its inner awaiter onto an executor.

WriteCallback

Handles data writes for an AsyncTransport.

after_cleanup_capture

Capture wrapper marked after_cleanup_ to bar refs from outliving cleanup.

after_cleanup_capture

Capture wrapper marked after_cleanup_ to bar refs from outliving cleanup.

after_cleanup_capture_heap

Heap‐backed after_cleanup_capture for cleanup‐free in‐place arguments.

after_cleanup_capture_indirect

Pointer‐holding after_cleanup_capture with reach‐through dereference sugar.

async_closure_config

Learn more about coro/safe tools by browsing docs/. Start with README.md and AsyncClosure.md. Here's a tl;dr for AsyncClosure.h.

async_closure_private_t

Tag type used by async_closure to trigger cleanup of capture`s that have an `co_cleanup(async_closure_private_t) overload.

await_result

Metafunction yielding the result type of co_awaiting an Awaitable.

awaiter_type

awaiter_type<Awaitable>

capture

Lifetime‐safe wrapper owning a captured value or reference for coroutines.

capture

Lifetime‐safe wrapper owning a captured value or reference for coroutines.

capture_heap

Heap‐backed capture letting cleanup‐free closures take in‐place arguments.

capture_indirect

Capture over a pointer, adding sugar so */`‐>` reach through one level.

co_cleanup_capture

Capture of a cleanup arg, whose refs downgrade dependents to after‐cleanup.

co_cleanup_capture

Capture of a cleanup arg, whose refs downgrade dependents to after‐cleanup.

co_cleanup_fn

A customization point that allows to provide an async cleanup function for a type. folly::coro::AutoCleanup uses co_cleanup_fn as the default cleanup function, so it is enough to define co_cleanup for a type to be able to use it with AutoCleanup.

co_error

Wraps an exception to be thrown from a coroutine via co_yield.

co_invoke_fn

Function object that invokes a callable and awaits its coroutine result.

co_result

Wraps a Try or result to be yielded from a coroutine as its completion.

co_result

Wraps a Try or result to be yielded from a coroutine as its completion.

co_safe_point_t

A semi‐awaitable type which, when awaited in an async coroutine supporting safe‐points, causes a safe‐point to be reached.

co_stopped_may_throw_t

Tag type that converts to a co_error carrying OperationCancelled.

is_auto_cleanup

Trait detecting whether T is an AutoCleanup wrapper.

is_awaitable

is_awaitable<T>::value is_awaitable_v<T>

is_awaiter

is_awaiter<T>::value is_awaiter_v<T>

is_semi_awaitable

Trait detecting whether T is a semi‐awaitable.

now_task

An immovable Task<T> that must be `co_await`ed in the expression that created it.

now_task_with_executor

The executor‐bound, immovable counterpart of now_task awaited in place.

on_stopped_and_error_t

Primary policy struct: specify behavior for stopped (cancellation) and error. Use via the variable templates below, not directly.

ready_awaitable

An awaitable that is immediately ready and yields a stored value on resume.

remove_reference_wrapper

A type trait to unwrap a std::reference_wrapper<T> to a type T

restricted_co_cleanup_capture

Restricted view on a co_cleanup_capture ref that avoids the safety downgrade by only accepting maybe_value args.

restricted_co_cleanup_capture

Restricted view on a co_cleanup_capture ref that avoids the safety downgrade by only accepting maybe_value args.

safe_async_scope_context_proxy

Proxy granting safe access to an async scope's context.

safe_task

Why is SafeTask.h useful?

safe_task_with_executor

A safe_task that has been bound to an executor and is ready to run.

value_or_fatal

value_or_fatal<Task<T>, Policy> wraps a task to guarantee value‐only completion.

variant_awaitable

An awaitable backed by one of several possible underlying awaitables.

will_fatal_t

Tag for "terminate on this completion".

Type Aliases

Name

Description

CleanableAsyncGenerator

An AsyncGenerator that requires cleanup() to be called before destruction.

NowTask

Backwards‐compatibility alias for now_task.

NowTaskWithExecutor

Backwards‐compatibility alias for now_task_with_executor.

SharedMutex

The default SharedMutex is SharedMutexFair.

auto_safe_task

Coros declared as safe_task<Safety, T> will satisfy the strong constraints above, or fail with a compile error.

await_result_t

Alias for the result type of co_awaiting an Awaitable.

awaiter_type_t

await_result<Awaitable>

capture_ref_conversion_t

Given a cvref‐qualified capture type, what capture reference type is it convertible to? The input value category affects the output reference type exactly as you'd expect for types NOT wrapped by capture. But, additionally, this knows to pick the correct wrapper: ‐ co_cleanup_capture inputs become co_cleanup_capture<SomeRef> ‐ after_cleanup_ref_* inputs become after_cleanup_capture<SomeRef> ‐ everything else becomes just capture<SomeRef>

closure_task

A safe_task meant to be the inner coro wrapped in an async_closure.

co_cleanup_safe_task

A safe_task that can be added to safe_async_scope, and may run during closure cleanup. Its content must therefore be co_cleanup_safe_ref‐safe.

co_current_cancellation_token_t

Placeholder type awaited to obtain the current coroutine's cancellation token.

co_current_executor_t

Placeholder type awaited to obtain the current coroutine's executor.

co_reschedule_on_current_executor_t

Placeholder type awaited to reschedule the current coroutine onto its executor.

member_task

A safe_task for non‐static member coroutines on stateful classes.

remove_reference_wrapper_t

Alias for the unwrapped type of remove_reference_wrapper.

semi_await_result_t

The result type of co_awaiting a semi‐awaitable T.

semi_await_try_result_t

The result type of co_awaiting the Try wrapper of a semi‐awaitable T.

value_only_awaitable_t

True for awaitables that only complete with value (not stopped or error)

value_task

A safe_task whose args and return type follow value semantics.

Functions

Name

Description

accumulate

accumulate overloads

async_closure

Creates a lifetime‐safe async closure task from bound args and a coroutine.

async_closure_make_cleanup_tuple

async_closure_resolve_backref

async_closure_set_cancel_token

async_now_closure

Creates an immediately‐awaited async closure returning a now_task.

blocking_wait

blocking_wait overloads

co_awaitTry

co_awaitTry overloads

co_nothrow

Cheaply propagate exceptions from awaitable to the calling coroutine, bypassing the expensive throw/catch stack unwinding mechanism.

co_scope_exit

Creates a scope‐exit coroutine running action with the captured state.

co_transition_lock

Async version of the folly::transition_lock TODO: add more transition policies beyond just from upgrade to exclusive

co_viaIfAsync

co_viaIfAsync overloads

co_withCancellation

co_withCancellation overloads

co_withExecutor

co_withExecutor overloads

collectAll

Concurrently await multiple awaitables and complete with a tuple of results.

collectAllRange

collectAllRange overloads

collectAllTry

Concurrently await multiple awaitables and complete with a tuple of Try results.

collectAllTryRange

collectAllTryRange overloads

collectAllTryWindowed

collectAllTryWindowed overloads

collectAllWindowed

collectAllWindowed overloads

collectAny

Concurrently await awaitables and complete with the first result and index.

collectAnyNoDiscard

Concurrently await awaitables and return every result once one finishes.

collectAnyNoDiscardRange

collectAnyNoDiscardRange overloads

collectAnyRange

collectAnyRange overloads

collectAnyWithoutException

Concurrently await awaitables, returning the first success or last error.

collectAnyWithoutExceptionRange

collectAnyWithoutExceptionRange overloads

concat

Concatenate the values from multiple streams into a single stream such that each stream is exhausted before the next one begins.

detachOnCancel

detachOnCancel is used to handle operations that are hard to be cancelled. A typical use case is: The caller starts a task with timeout (in this case, 1 sec timeout). The task itself launches a long running job and the job doesn't handle cancellation (sleep_for in this example). The caller has timeout and the cancellation is propagated to the task. The detachOnCancel detects the cancellation and return immediately. However, the background task still runs until the thread join.

detect_promise_return_object_eager_conversion

Returns whether the compiler converts a coroutine promise return object eagerly.

filter

Filters a stream, yielding only values that satisfy the predicate.

get_awaiter

get_awaiter overloads

makeErrorTask

Make a Task that will trivially yield an Exception.

makeFuture

makeFuture overloads

makePromiseContract

makePromiseContract can help you migrating your non‐coroutine code base to coroutine. If your code already uses Future/SemiFuture, you don't need this tool. A common use case is with async callback functions. In the example, we can pass a callback function into the legacy code sleepAndNotify and sleepAndNotify sets the promise on completion. Consider to use detachOnCancel with this makePromiseContract to handle long running (longer than your timeout) tasks that don't handle cancellation properly.

makeResultTask

Make a Task out of a Try.

makeTask

makeTask overloads

makeUnorderedAsyncGenerator

makeUnorderedAsyncGenerator overloads

makeUnorderedTryAsyncGenerator

makeUnorderedTryAsyncGenerator overloads

make_error_now_task

Make a now_task that will trivially yield an exception.

make_now_task

make_now_task overloads

merge

Merges a stream of input streams into a single interleaved output stream.

retryN

retryN overloads

retryWhen

Execute a given asynchronous operation returned by func(), retrying it on failure, if desired, after awaiting retryDelay(error).

retryWithExponentialBackoff

retryWithExponentialBackoff overloads

scheduleAutoCleanupIfNeeded

Schedules async cleanup for any AutoCleanup arguments on the coroutine.

sleep

Return a task that, when awaited, will sleep for the specified duration.

sleepReturnEarlyOnCancel

Return a task that, when awaited, will sleep for the specified duration.

swap

Swaps the state of two generators.

tag_invoke

tag_invoke overloads

timed_wait

Awaits awaitable, giving up after duration elapses.

timeout

Returns a Task that, when started, starts a timer of duration 'timeoutDuration' and awaits the passed SemiAwaitable.

timeoutNoDiscard

Returns a Task that, when started, starts a timer of duration 'timeoutDuration' and awaits the passed SemiAwaitable (operation).

toFuture

Converts the given SemiAwaitable to a Future, starting it on the Executor.

toSemiFuture

Converts the given SemiAwaitable to a SemiFuture (without starting it).

toTask

toTask overloads

toTaskInterruptOnCancel

toTaskInterruptOnCancel overloads

to_now_task

to_now_task overloads

value_or_error

When awaited, returns a result<T> in a value or an error state, but never has_stopped() (aka OperationCancelled). If awaitable reports as "stopped", the awaiting coroutine will be promptly torn down, **without throwing**, and its parent will in turn receive a "stopped" completion.

value_or_error_or_stopped

When awaited, returns result<T> just like value_or_error(), but also captures "stopped" completions, so you must test for has_stopped().

Variables

Name

Description

co_cancelled [deprecated]

Deprecated alias for co_stopped_may_throw.

co_current_async_stack_trace

Awaitable yielding the current async stack trace when co_awaited.

co_current_cancellation_token

Placeholder value awaited to obtain the current coroutine's cancellation token.

co_current_executor

Special placeholder object that can be 'co_await'ed from within a Task<T> or an AsyncGenerator<T> to obtain the current folly::Executor associated with the current coroutine.

co_reschedule_on_current_executor

A SemiAwaitable object that allows you to reschedule the current coroutine onto the currently associated executor.

co_safe_point

A semi‐awaitable value that causes a safe‐point to be reached when awaited.

co_stopped_may_throw

Tag that, when thrown via co_yield, cancels the awaiting coroutine.

is_auto_cleanup_v

True when T is an AutoCleanup wrapper.

is_awaitable_async_stack_aware_v

True if the awaitable customizes the co_withAsyncStack CPO.

is_awaitable_v

True if T satisfies the awaitable interface.

is_awaiter_v

True if T satisfies the awaiter interface.

is_semi_awaitable_v

True if T is a semi‐awaitable.

on_stopped

Convenience: stopped returns V, error terminates (fatal).

on_stopped_and_error

Policy that returns Stopped on cancellation and Error on error.

on_stopped_void

Convenience for void tasks: stopped returns unit, error terminates.

value_only_awaitable_v

True if T only completes with a value (not stopped or error).

will_fatal

Policy value selecting termination on a stopped or error completion.

Using Declarations

Name

Description

coroutine_handle

Re‐exports the standard coroutine handle type.

coroutine_traits

Re‐exports the standard coroutine traits template.

noop_coroutine

Re‐exports the standard no‐op coroutine factory.

noop_coroutine_handle

Re‐exports the standard no‐op coroutine handle type.

noop_coroutine_promise

Re‐exports the standard no‐op coroutine promise type.

suspend_always

Re‐exports the standard always‐suspend awaitable.

suspend_never

Re‐exports the standard never‐suspend awaitable.

Created with MrDocs