Frame Allocators
Every task you start allocates a coroutine frame, and a server that starts many short tasks pays that cost on each one. Capy routes these allocations through a frame allocator. The execution context’s default, recycling_memory_resource, recycles freed frames, so steady-state work rarely reaches the heap. thread_pool uses std::allocator<void> instead unless you change it. This page explains the choices you have, and then the mechanism that carries the allocator to every frame in a chain.
Using Custom Allocators
With run_async
Pass an allocator to run_async:
std::pmr::monotonic_buffer_resource resource;
std::pmr::polymorphic_allocator<std::byte> alloc(&resource);
capy::run_async(executor, alloc)(my_task());
Or pass a memory_resource* directly:
std::pmr::monotonic_buffer_resource resource;
capy::run_async(executor, &resource)(my_task());
Default Allocator
When no allocator is specified, run_async uses the execution context's frame allocator. An execution context starts with recycling_memory_resource, which is optimized for coroutine frame sizes. A context may replace it: thread_pool uses std::allocator<void>. Call set_frame_allocator on the context to choose another.
Custom Allocator Requirements
Custom allocators must meet the usual C++ allocator requirements, or be a std::pmr::memory_resource*. The library does not expose a separate public concept for them; a value-type allocator works as a frame allocator when it provides, illustratively:
typename A::value_type;
a.allocate(n) // -> A::value_type*
a.deallocate(p, n);
The allocator must also be copy constructible. When passed to run_async, it must be nothrow move constructible as well. Capy checks both at compile time.
Frames allocated through a value-type allocator are aligned to the default new alignment (STDCPP_DEFAULT_NEW_ALIGNMENT, 16 bytes on common platforms). Capy rebinds the allocator to another value_type and requests whole multiples of that alignment, so each request’s size is rounded up. Frames that need more alignment are not supported.
Recycling Memory Resource
Capy provides recycling_memory_resource, a memory resource optimized for coroutine frames:
-
Maintains freelists by size class
-
Reuses recently freed blocks (cache-friendly)
-
Sends requests over 2048 bytes, and misses in both its pools, to
::operator new
An execution context uses this resource by default. thread_pool replaces it with std::allocator<void>.
recycling_memory_resource honors only the default new alignment (STDCPP_DEFAULT_NEW_ALIGNMENT, 16 bytes on common platforms). The alignment argument passed to do_allocate/do_deallocate is ignored, so over-aligned requests are not satisfied. This is sufficient for coroutine frames but means the resource is not a drop-in replacement where over-aligned allocations are required.
|
Observing Reuse
This memory_resource pools each freed block by size and counts how many allocations come from the heap versus a recycled block:
// A memory resource that pools freed blocks by size. When a coroutine
// frame is freed, its block is kept; the next frame of the same size
// reuses it instead of allocating again -- the strategy that makes
// recycling_memory_resource fast. The two counters let the test observe
// upstream allocations versus reuse.
struct pooling_resource : std::pmr::memory_resource
{
std::size_t upstream = 0; // blocks taken from the heap
std::size_t reused = 0; // blocks served from the freelist
void*
do_allocate(std::size_t bytes, std::size_t) override
{
auto& blocks = pool_[bytes];
if(! blocks.empty())
{
++reused;
void* p = blocks.back();
blocks.pop_back();
return p;
}
++upstream;
return ::operator new(bytes);
}
void
do_deallocate(void* p, std::size_t bytes, std::size_t) override
{
pool_[bytes].push_back(p); // keep the block for the next frame
}
bool
do_is_equal(memory_resource const& other) const noexcept override
{
return this == &other;
}
~pooling_resource() override
{
for(auto& [bytes, blocks] : pool_)
for(void* p : blocks)
::operator delete(p);
}
std::unordered_map<std::size_t, std::vector<void*>> pool_;
};
Run the same task eight times through it, one run at a time:
// Run the same task repeatedly through one pooling resource. The
// first run has an empty pool, so its frames come from upstream.
// Once the task completes, its frames go back into the pool, so
// every later run reuses a freed block of the right size.
pooling_resource pooling;
auto run_once = [&]
{
capy::thread_pool pool(1);
capy::run_async(pool.get_executor(), &pooling)(my_task());
pool.join(); // task done: its frames are back in the pool
};
run_once(); // cold: fills pool
std::size_t const upstream_when_warm = pooling.upstream;
for(int i = 0; i < 7; ++i)
run_once(); // warm: reuses pool
The first run finds an empty pool and takes its coroutine frames from the heap. Each pool.join() returns after the task has finished and its frames are back in the resource, so the next run_async call reuses them. Once the pool is warm, the upstream count stops climbing while the task keeps running — the seven warm runs allocate nothing new. recycling_memory_resource does the same thing with size-class freelists and a lock-free thread-local cache.
HALO Optimization
Heap Allocation eLision Optimization (HALO) allows the compiler to allocate coroutine frames on the stack instead of the heap when:
-
The coroutine’s lifetime is provably contained in the caller’s
-
The frame size is known at compile time
-
Optimization is enabled
Capy’s task<T> uses the [[clang::coro_await_elidable]] attribute (when available) to enable HALO:
template<typename T = void>
struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE
task
{
// ...
};
When HALO Applies
HALO is most effective for immediately-awaited tasks:
// HALO can apply: task is awaited immediately
int result = co_await compute();
// HALO cannot apply: task escapes to storage
auto t = compute();
tasks.push_back(std::move(t));
Measuring HALO Effectiveness
An elided frame never reaches the frame allocator. To see whether HALO applies, start the task with a counting memory_resource, such as the one in Observing Reuse. Then compare its allocation count with the number of tasks the code creates.
Best Practices
Use Default Allocators
For most applications, the execution context’s frame allocator provides good performance without configuration. To use the recycling resource on a thread_pool, pass get_recycling_memory_resource to its set_frame_allocator.
Consider Memory Resources for Batched Work
When starting many short-lived tasks together, a monotonic buffer resource can be efficient:
void process_batch(std::vector<item> const& items)
{
std::array<std::byte, 64 * 1024> buffer;
std::pmr::monotonic_buffer_resource resource(
buffer.data(), buffer.size());
for (auto const& item : items)
{
capy::run_async(executor, &resource)(process(item));
}
// The resource is released here, so every task must have finished
}
The resource must outlive every task started with it, including the unwind of any that are abandoned. With an executor that runs each task inline, this function returns after its tasks finish. With an executor that queues the work, keep the resource alive until the tasks have finished. See Shutdown Ordering.
Scope Variables to Reduce Frame Size
Clang decides frame layout after optimization, so declaration scope controls what it keeps. A variable whose scope spans a co_await stays in the frame until that scope ends.
Wrapping buffer usage in explicit braces can therefore cut frame size sharply:
// BAD: buf lives in frame across all subsequent co_awaits
capy::task<> process(stream& s)
{
char reply[] = "ok";
char buf[4096];
auto [ec, n] = co_await s.read_some(buf);
co_await do_work(buf, n);
co_await s.write_some(reply); // buf wastes 4K in frame
}
// GOOD: braces end buf's lifetime before next suspend
capy::task<> process(stream& s)
{
char reply[] = "ok";
{
char buf[4096];
auto [ec, n] = co_await s.read_some(buf);
co_await do_work(buf, n);
}
co_await s.write_some(reply); // 4K saved
}
The same technique lets Clang overlap two variables. When their lifetimes cannot coexist, both can occupy one frame offset:
// BAD: both arrays in frame simultaneously (8K)
capy::task<> pipeline(stream& in, stream& out)
{
char read_buf[4096];
auto [ec1, n] = co_await in.read_some(read_buf);
char write_buf[4096];
prepare(write_buf, read_buf, n);
co_await out.write_some(write_buf);
}
// GOOD: non-overlapping scopes allow frame reuse (4K)
capy::task<> pipeline(stream& in, stream& out)
{
std::size_t n;
{
char read_buf[4096];
auto [ec, n_] = co_await in.read_some(read_buf);
n = n_;
}
{
char write_buf[4096];
prepare(write_buf, n);
co_await out.write_some(write_buf);
}
}
In the second version, read_buf and write_buf never coexist, so they can share storage. This applies to any variables with non-overlapping lifetimes, not just arrays.
|
Both techniques are Clang optimizations, and both need Frame bytes for the four coroutines above, reported by the promise’s
On GCC, scoping does not shrink the frame. Keep large buffers out of the coroutine instead: pass them in by reference, or allocate them outside the frame. |
GCC vs Clang Frame Sizes
| This section draws on C++20 Coroutines from compiler and library authors' perspective by Chuanqi Xu. |
GCC and Clang use fundamentally different strategies for coroutine frame layout:
-
Clang performs frame layout after middle-end optimizations. Dead variables, unused temporaries, and constant-folded intermediates are eliminated before the frame is sized.
-
GCC performs frame layout in the frontend, before optimizations. Every local variable whose scope spans a suspend point ends up in the frame, even if optimizations would later prove it dead.
How large the gap gets depends on how much the optimizer can discard. Without optimization the two are comparable, as the table above shows. With optimization enabled, Clang’s frames can be smaller by an order of magnitude or more. The cited article reports a coroutine whose frame was 24 bytes on Clang against 16,032 bytes on GCC.
For production coroutine workloads, Clang currently produces substantially better code. On GCC, do not rely on scoping; keep large buffers outside the frame, and consider a custom memory_resource with larger block sizes. Frames above 2048 bytes bypass the default recycling memory resource’s pooling.
How Frame Allocation Works
The sections below are the mechanism behind everything above. You do not need them to use a custom allocator, but you do need them to write an executor or a promise type.
The Timing Constraint
Coroutine frame allocation has a unique constraint: memory must be allocated before the coroutine body begins executing. The standard C++ mechanism, the promise type’s operator new, is called before the promise is constructed.
How can a coroutine use a custom allocator when the allocator might be passed as a parameter, which is stored in the frame?
Thread-Local Propagation
Capy solves this with a per-thread frame allocator pointer, kept in thread-local storage (TLS):
-
Before the task argument is evaluated,
run_asyncinstalls its allocator in TLS.rundoes the same when given an allocator. -
The task’s
operator newreads that allocator. It stores the allocator at the tail of the frame, so the frame is freed through the same resource. -
The starting function also gives the task an environment that carries the allocator. By the end of the expression that started the task, it restores the TLS value it found.
This is why run_async uses two-call syntax:
capy::run_async(executor)(my_task());
// ↑ ↑
// 1. Sets 2. Task allocated
// TLS using TLS allocator
Three patterns split those two calls apart, and two of them do it without any diagnostic. Starting Coroutines lists all three.
Reinstalling on Resume
A task never relies on TLS still holding its allocator. The task is lazy, so its body may start later or on another thread. When the body starts, the task reinstalls TLS from its environment. It does so again each time it resumes from a co_await.
A child task created in the body therefore allocates from the parent’s allocator, whichever thread runs the body and whenever it runs. Awaiting the child hands it the parent’s environment, so the child does the same for its own children.
TLS Preservation
Between a coroutine’s await_resume (which sets TLS to the correct allocator) and the next child coroutine invocation (whose operator new reads TLS), arbitrary user code runs. That code can call .resume() directly, pump a completion queue, or run nested dispatch. If it resumes a coroutine from a different chain on the same thread, the other coroutine’s await_resume overwrites TLS with its own allocator. The original coroutine’s next child would then allocate from the wrong resource.
To prevent this, any code that calls .resume() on a coroutine handle must use safe_resume from <boost/capy/ex/frame_allocator.hpp>:
// In your event loop or dispatch path:
capy::safe_resume(h); // saves and restores TLS around h.resume()
safe_resume saves the current thread-local allocator, calls h.resume(), then restores the saved value. This makes TLS behave like a stack: nested resumes cannot spoil the outer value. All of Capy’s built-in executors (thread_pool, strands, blocking_context) use safe_resume internally. Custom executor event loops must do the same — see Custom Executor for an example.
|
The cost is two TLS accesses (one read, one write) per Two
|
Frame Allocator Mixin
Most users never need to allocate coroutine frames manually — task<T> and the built-in awaitable types already participate in TLS frame allocation. When you write your own coroutine promise type and want it to use the same fast path, inherit from frame_alloc_mixin:
struct my_coroutine
{
struct promise_type : capy::frame_alloc_mixin
{
// get_return_object, initial_suspend, ...
};
};
frame_alloc_mixin (in <boost/capy/ex/frame_alloc_mixin.hpp>) supplies operator new and operator delete that:
-
Read the thread-local frame allocator set by
run_asyncorrun(falling back tostd::pmr::get_default_resource()when none is set). -
Bypass virtual dispatch when that allocator is the default recycling memory resource.
-
Store the resolved allocator pointer at the tail of each frame, so deallocation uses the correct resource even if the thread-local allocator has since changed.
This is the same strategy used internally by context_awaitable_promise_base. Use the mixin directly when your promise type does not need the full environment and continuation support that context_awaitable_promise_base provides. The allocation fast path uses thread-local storage and needs no synchronization; the global pool fallback is mutex-protected.