folly::coro::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.

Synopsis

Declared in <folly/coro/safe/AsyncClosure.h>

struct async_closure_config;

Description

Use async_closure() / async_now_closure() only when now_task is not enough. For your effort, you get (1) guaranteed, exception-safe async RAII, and (2) the resulting coro is an automatically-measured movable safe_task, which improves lifetime safety (LifetimeSafetyBenefits.md).

Control flow matches a regular now_task lazy-start coro:

  • All "argument-binding" and "coro creation" work is eager.

  • Your inner task & subsequent cleanup can only run when awaited.

async_closure(bind::args{...}, taskFn) wraps an outer task around yours, unless elided via an automatic optimization. The outer task owns special "capture" args passed to the closure, ensuring they outlive the inner task.

Lifecycle contract:

  • bind::args{} evaluate left-to-right (L2R) due to {}.

  • Construction of bind::capture_in_place / bind::in_place args is also L2R.

  • When args are passed to the inner coro, copy/move order is unspecified.

  • Upon awaiting the inner coro, setParentCancelToken() is called on the capture args in L2R order.

  • After the inner coro exits, arg co_cleanup() is executed in R2L order.

  • When the outer coro exits, captures are destroyed in R2L order.

The co_cleanup() and setParentCancelToken() protocols support capture types like safe_async_scope and BackgroundTask, which give the user guaranteed, exception-safe async cleanup. Before building custom async RAII, carefully read CoCleanupAsyncRAII.md.

The async_closure_make_outer_coro machinery is reused by AsyncObject, which implements a similar "async RAII" contract for object scopes.

The difference between async_closure() and async_now_closure() is that the former measures argument & inner coro safety, and makes a safe_task, while the latter has no safety checks, and makes a now_task. Both make it easy to write lifetime-safe code.

Data Members

NameDescription
force_outer_coro POWER USERS ONLY: For efficiency, async_closure will elide the outer coro if there are no co_cleanup captures. In particular, setParentCancelToken isn't currently part of this detection, since we don't expect it to be used without co_cleanup.