r/cpp • u/rhidian-12_ Coroutines4Life • Feb 21 '26
Implementing your own asynchronous runtime for C++ coroutines
Hi all! Last time I wrote a blog post about writing your own C++ coroutines. Now, I wanted to highlight how to write your own C++ asynchronous runtime for your coroutines.
https://rhidian-server.com/how-to-create-your-own-asynchronous-runtime-in-c/
Thanks for reading, and let me know if you have any comments!
42
Upvotes
View all comments
Show parent comment
1
u/trailing_zero_count async enthusiast | TooManyCooks author Feb 21 '26 edited Feb 21 '26
Looks OK to me, but I haven't tested with any C++23 features yet. If true, then this is a useful workaround. Thanks for sharing! It does have a couple downsides though: 1. It's unintuitive and safety is enforced by convention; if you remove the "this auto" parameter it will still compile, but now behave wrongly. 2. It may have negative performance implications if a large lambda object with multiple captures is actually materialized on the stack and then copied into the coroutine frame, vs. just passing each individual capture as a separate parameter. The compiler may be able to elide this copy (?) but it definitely won't in debug builds.
I'm not sure about this. Theoretically it would work if the lambda object was implicitly passed by reference as a coroutine parameter, and reference lifetime extension keeps the lambda object alive to the end of the full-expression. However from the original GCC thread about this, they state that the lambda object is passed as a pointer (essentially "this" pointer), so lifetime extension would not occur.
I wasn't able to find a source that corroborates your statement or even discusses this specific edge case in detail. If you could share one, I'd love to read it. With that said, even if this does work - it's SO RISKY because then all kinds of reasonable refactors which involve breaking the lamba call and co_await expression into separate lines will break it.
Do you have a source for this? It doesn't make sense to me. Since the temporary is created in the parent's scope, and the parent co_awaits the entire child coroutine, there's no way for the parent to "look inside" the child coroutine to know that it can destroy the temporary after the child's first suspension point. The parent doesn't get resumed until after the entire child is completed.
(unless you are using eager coroutines - in which case the parent task actually RUNS the child coroutine directly until the first suspension point. Again, this is confusing and don't do it. There's a reason I don't offer eager coroutines in my library at all. They are too difficult to reason about, have unreliable performance characteristics, and offer weird hacks like what you've described.)
Once you remove eager coroutines from the picture and think only of coroutines as "a function that returns an object" (where the object is a lazy coroutine that has not yet been started), the behavior is more obvious.