19

First of all I want to predict the memory usage of my code, just as any responsible programmer should. This would apply even if I was not deciding to allocate my coroutine frames using placement new, as I am (see below pseudocode). Even supposing I change my mind about placement-newing all my coroutines, and thus I let the complier allocate all my coroutines on the heap, I'd still want the C++ language to tell me how much heap I'm going to eat up by that.

But, IRL, I'm targeting a high-reliability and embedded environment. There might not even be a heap, so...

struct coroutine_return_type
{
  struct promise_type
  {
    void *operator new(std::size_t sz, char *buf, std::size_t szbuf)
    {
      if (sz > szbuf)
        throw std::bad_alloc{};
      return buf;
    }
    void operator delete(void *)
    {
    }
    // ...
  };
  // ...
};

coroutine_return_type my_coroutine(char *, std::size_t)
{
  // The arguments, char * and std::size_t,
  // have been fowrarded to promise_type::operator new
  // but here in the coroutine body they aren't used again...
  for ( ; ; )
    co_yield /* something */;
}

struct coroutine_instance_type
{
  char my_coroutine_frame[ /* WHAT? */ ];
  coroutine_return_type my_coroutine_instance;
  coroutine_instance_type()
    : my_coroutine_instance{my_coroutine(my_coroutine_frame, sizeof(my_coroutine_frame))}
  {
    // ...
  }
  // ...
};

WHAT I WANT

I want a complie-time expression to return an upper bound on my coroutine size, to replace /* WHAT? */.

STUPID SOLUTION

There's an obviously stupid way to (not quite) do what I want:

  1. Subclass std::bad_alloc. Then throw std::bad_alloc{} in my operator new becomes throw std::my_bad_alloc{sz}. The catch block can call my_bad_alloc_instance.get_parameter() to learn what sz was inside operator new.

  2. Call my_coroutine(nullptr, 0) and catch the exception.

What's stupid about this (nonexhaustive list):

It's not a compile-time expression, because it has to "return" its value using a throw and throw can never be used in a complie-time expression. But the replacement for /* WHAT? */ in my pseudocode needs to be a compile-time expression.

It's a sample, not an upper bound. Suppose the actual, allocated size of the coroutine frame depends on conditions at run-time. (Now, I don't anticipate that different coroutine sizes for different run-time conditions, will ever actually occur in my IRL applcation, but according to the C++ standard it seems to be possible.) In that case, it's insufficient to just learn what size is actually passed to operator new. The required expression would have to return, instead, an upper bound on what could be passed to operator new.

So, in summary:

SUMMARY OF THE QUESTION

What tools does the C++ language provide to query the size of a coroutine frame? The ideal tool should be a compile-time expression for allocating non-heap memory to the coroutine, or alternatively, the same tool would serve as well for bounding the amount of heap.

5
  • 3
    "I'm targeting a high-reliability and embedded environment. There might not even be a heap" Are you sure that you want to use co_await-style coroutines at all in such an environment? If every byte and cycle is that precious, I would avoid C++ mechanism whose performance characteristics are indeterminate. Just like you'd avoid dynamic_cast, typeid, and such. Jul 2, 2020 at 21:47
  • @NicolBolas Because co_await beats std::thread.
    – cs-
    Jul 3, 2020 at 4:30
  • 1
    @cs-: ... what? co_await coroutines are nothing more than a mechanism to pause and resume a function's execution. They do not inherently have anything to do with threading. Now, their primary designed purpose is to facilitate the use of asynchronous continuations. But continuations start from the assumption that a thread already exists and is going to be doing something, so you want this function to execute after the thing executing in that thread is complete. They're not a replacement for std::thread or any other thread-creation mechanism. Jul 3, 2020 at 4:35
  • 1
    @NicolBolas Think, "I got N chores to do. While one chore is blocking for its next event, another chore should run until all chores block." You're gonna be my hero today if you got a third way, after (first way) spawn a thread for each chore and let the OS schedule them and (second way) stay on one thread but implement each as a continuable function and schedule them yourself.
    – cs-
    Jul 3, 2020 at 16:23
  • @cs-: What you've described hardly requires giving each "chore" its own thread. What you're talking about is resumable tasks and a manager for handing them off to different threads. While co_await makes such things (much) easier to code and reason about, it's not like resumable task parallelism is a new field of study. The traditional method tends to involve explicit continuation functions or fully-fledged fibers (which are much larger than any co_await coroutine's stack). co_await is a good fit for your needs, but you have to accept a lack of control that comes with it. Jul 3, 2020 at 16:41

3 Answers 3

15

This was debated at length during the standardization of C++20 coroutines. The layout and size of the coroutine frame cannot be determined until after the optimizer finishes its job, and making that information available to the frontend would require fundamental rearchitecturing of all existing compilers. Implementers reported that not even a (useful) upper bound is feasible.

See parts 2 and 4 of P1365R0 for a discussion on ways to use coroutines in environments where no dynamic memory allocation is allowed.

9
  • Thanks for the paper. I'm going to summarize the most useful suggestion from it: Use a heap, but the first thing to be done on program startup is create every coroutine, then never delete them (and never allocate anything else on the heap, either). This satisfies high reliability because the unreliability of a heap comes from trying to allocate a large object in fragmented memory. Thus if you never fragment your heap in the first place, you can get away with it. A sane allocator might even allocate the coroutines sequentially.
    – cs-
    Jul 3, 2020 at 16:41
  • @cs-: "the first thing to be done on program startup is create every coroutine, then never delete them" And what happens if one coroutine calls another? Or a coroutine recursively calls itself (which is 100% OK)? You can code this way, but it is incredibly fragile and requires adherence to very particular discipline. You won't be able to just use co_await where appropriate; every time you use it, you have to think about all of the possible call graphs and so forth. Jul 3, 2020 at 16:44
  • @NicolBolas Well, no... the discipline is only on coroutine creation, and the creation is straightforward as long as you know at startup time what coroutines you need. There will be no extra constraints on coroutine resumption.
    – cs-
    Jul 3, 2020 at 17:34
  • @cs-: I think you may be confusing how co_await coroutines work, because "creation" is a very ephemeral process. A coroutine is "created" when you call a function as an implementation detail of that function being a coroutine. A coroutine is resumed... well, whenever your promise/future objects dictate. So if you're doing what you describe, you cannot simply call it like a regular function (the way a coroutine is supposed to work). You have to exercise discipline to avoid calling coroutine functions the way you normally call other functions; you have to interact with the future. Jul 3, 2020 at 17:39
  • @Nicol Bolas: I don't think this is a fair comment. Being a coroutine isn't merely an implementation detail because coroutines have to have an awaitable return type. So at the very least you can say from outside when a function isn't a coroutine. Furthermore, resuming a coroutine is distinct from calling it, so it is quite straightforward to ensure that coroutines are called at program initialization.
    – sh-
    Sep 2, 2020 at 20:35
4

What tools does the C++ language provide to query the size of a coroutine frame?

None. What you want is impossible by design.

co_await coroutines in C++ are designed in such a way that being a coroutine is an implementation detail of the function. From just a function declaration, it is impossible to know if a function is a coroutine or if it just happens to have a signature that could use the various coroutine machinery. The feature is meant to work in such a way that it's effectively none of your business if a function is or is not a coroutine.

Being able to determine the size of a coroutine frame would first require being able to identify a coroutine. And since the system is designed such that this is impossible... well, there you are.

1
  • One might want to add that boost::asio has a library-based implementation of stackless coroutines that - besides having various disadvantages - has the advantage that the state is explicit and its size is known at compile time. This makes it easy to avoid dynamic allocation in use cases like mentioned by the OP.
    – sh-
    Sep 2, 2020 at 20:39
2

As Nicol Bolas mentioned it is not possible to get it as a constexpr value. But this is not possible for "normal functions", too. There is just one rule "don't store big objects on the stack to avoid stackoverflows".

As a role of thumb the maximum of the required heap storage is the size of your local variables that must be available after the first continuation and eventually some small "management-fields" to store the contunation-point (usually some kind of int).

But our compilers are nowadays really smart and optimize the heap allocations completely away - so you should not worry to much about it.

2
  • The heap allocation can't be elided when the coroutine has to live longer than the function that created it.
    – cs-
    Jul 3, 2020 at 16:02
  • 1
    Coroutines lives always longer than the "creating function". Heap storage can often be elided in case of generator functions (co_yield) after "inlining" -> variables are moved to the caller stackframe
    – Bernd
    Jul 4, 2020 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.