Coroutines mean that the thing that looks like a stack variable may not technically be one


Some time ago, I pointed out the Get­Current­Thread­Stack­Limits function which lets you determine whether a pointer points into the stack.

Note, however, that if the local variable is captured by a coroutine, The introduction of coroutines into the C++ language means that what looks like a local variable may end up being hoisted into a heap-allocated object representing the coroutine itself (like, say, a std::future).

Something to bear in mind if you're going to be making decisions based on whether a variable is on the stack.

Comments (8)
  1. Jan Ringoš says:

    I’d guess that coroutines would be implemented through fibers on Windows.

    1. henke37 says:

      Look up the emulator formerly called bsnes. The madman behind it tried using fibers for coroutines. Then he just went ahead and swapped ESP. Pretty sure that you get into all sorts of “fun situations” by doing that. Lets hope he never had to verify that every stack frame was in on the joke of exceptions…

      1. creaothceann says:

        It’s still called bsnes, but just the emulator core. (higan is the whole suite, and libco is the coroutine library.)

    2. JAS says:

      The correct answer is you don’t implement coroutines any particular way and just adapt the language’s coroutine builder pattern to your specific scenario. I’d be pretty pissed if I wanted to handle thread pools and found out that some yo yo forced coroutines to use fibers. Fibers are worthless. They’re a computer science experiment. We heard a fiber story about SQL Server but that story hasn’t quite propagated to other projects, wonder why.

    3. camhusmj38 says:

      The coroutines ts refers to stackless coroutines. The compiler transforms the function into a state machine – when the coroutine suspends, it needs a place to store any local state that will be need after the courtine resumes. Unless the compiler can prove the coroutine will not be resumed after the frame in which it is first invoked, that state needs to be heap allocated.

      1. camhusmj38 says:

        Sorry, forgot to add – that means fibres aren’t the correct model. Coroutines run on whatever stack is handy.

        1. Jan Ringoš says:

          Ah, that makes more sense now. Thanks.

  2. GWO says:

    I’m afraid these things really have been hoisted into the future – Coroutines didn’t make the cut for inclusion in C++17

Comments are closed.

Skip to main content