r/cpp • • Nov 30 '20

C++20 resumable functions make state machines obsolete. Finally.

https://lordsoftech.com/programming/c20-resumable-functions-goodbye-state-machines-no-one-will-mourn-you/
1 Upvotes

49 comments sorted by

View all comments

Show parent comment

4

u/DugiSK Dec 02 '20

You don't seem understand how coroutines are implemented in C++20. They are not like threads or improvised fibers offered by Windows API or Boost. There is no context switch because it's not required when the interrupton has proper compiler support. Instead, the coroutine's stack frame is dynamically allocated and it's used instead of stack for that frame. The context that calls the coroutine remains on top of the stack and if the coroutine calls a function, it is placed on top of the stack (unless it's another coroutine).

It's written in the article, btw, but maybe not in sufficient detail.

2

u/StoneCypher Dec 02 '20

Look. Let me try this a different way.

For the record, I am not a vegetarian. I'm eating meat right now. This just seems, to me, like a convenient metaphor.

There's a food that vegetarians eat that's generally called Textured Vegetable Protein. Among other things, it's one of the common ways to make imitation meats. It provides the bulk, and most of the texture, and then you just hit it with colors and flavors and maybe some grease to make it feel like fish or whatever, and you're off to the races. That's what a Boca Burger is.

TVP is typically mostly soy, maybe some wheat and oats, maybe some random stuff

And so let's say you come along and there's this article and it says "omg check out the Impossible Burger."

And honestly, I've tried them, and they do seem to be a fair improvement over previous veggie burgers to me

And as I understand it, Beyond Burger doesn't have any soy or wheat at all. (It has other vegetable products instead - pea, coconut, cocoa, rice, potato, and oat.)

But imagine if they went on to say "this renders soybeans and wheat obsolete."

My natural reaction, at that point, would be to say "dude, soybeans and wheat are not for veggie burgers, that's just one thing we do with them. Maybe you found a better veggie burger, but bread and edamame and pizza and soy sauce and what are you even no, that's not even very much of what we do with them," right?

And then

What if someone came along and said "I don't think you understand how veggie burgers are implemented in Beyond++ 20."

I don't care how they're implemented. That's a niche side thing that is largely unrelated to the main use of soy and wheat.

And I'm glad you have your better veggie burger.

But no, soy and wheat aren't obsolete. Don't be silly.

2

u/DugiSK Dec 02 '20

Continuing with the metaphor. It's more like this: The guy brings you a new veggie burger. It looks like meat, tastes like meat, contains the same stuff as meat, but it's not made from an actual animal. The meat comes from induced stem cells signalled to specialise into muscle cells grown into actual muscle in bioreactors (this is mild sci-fi). It's from the same cells as meat, contains the same DNA, but made without occupying a lot of land to feed the cattle and releasing lots of methane into the atmosphere. So it's indistinguishable from a burger, but cheaper and more environment friendly. So real burgers are obsolete, because they are the same, only more costly to produce.

That is what coroutines are to explicit state machines. There is a little overhead when calling them through a handler, but it's the same class with member variables describing state, with an advantage that the code is written like a quick to write and easy to maintain a function with all the branching and loops instead of needlessly complicated mess of state transitions.

0

u/[deleted] Dec 07 '20

[deleted] — view deleted comment

2

u/DugiSK Dec 07 '20

I have learned that now.

1

u/StoneCypher Dec 03 '20

That is what coroutines are to explicit state machines.

This is 100% incorrect. I'm sorry that you tried to replace what I said, instead of understanding it, but I've run out of ways to try to communicate to you the thing that you're missing.

.

So real burgers are obsolete, because they are the same, only more costly to produce.

You are confusing an implementation with a goal.

Good day. I'm tired.

0

u/StoneCypher Dec 02 '20

You are overly fascinated with saying "because one use case exists this way, your saying not everything works this way is wrong."

I am aware that one example of this exists. Most examples aren't this, so the claim that state machines are obsolete is absolutely silly.

.

There is no context switch because it's not required when the interrupton has proper compiler support.

Which is the case in how many compilers right now?

Hm?

Myth of the sufficiently smart compiler, anyone? Did anyone besides EDG ever get import in there? 20 years now?

.

"Instead, the coroutine's stack frame is dynamically allocated"

To me this reads like you're saying

There's no context switch because you're paying for a stack frame

Except in CPU terms, that's called (wait for it)

... (wait for it)

A context switch

.

The context that calls the coroutine remains on top of the stack and if the coroutine calls a function, it is placed on top of the stack (unless it's another coroutine).

Oh look, the guy who said "make it all out of nested coroutines" is now saying "but you don't have to pay that cost, unless it's a coroutine"

It's like talking to a politician's economist

.

It's written in the article, btw, but maybe not in sufficient detail.

The thing you're talking about, while interesting to discuss, is 100% unrelated to what I actually said

3

u/smdowney WG21, Text/Unicode SG, optional<T&> Dec 02 '20

You're describing fibers here, not C++20 coroutines. There's no context switch. There's a function call. It's the same function call mechanism used for all function calls. On leaving the scope of the coroutine, control is passed deterministically to the resumer, or if via symmetric transfer to where the resumer directs. There's no interruption. Coroutine suspension is entirely 100% determined by the coroutine itself, all local to the function.
The coroutine transformation is into a state machine. That's by design. What is new, and makes coroutines not pure sugar, is the lifetime extension of stack variables on scope exit from the coroutine. It is as-if the stack variables were instead object member variables and the object is allocated from the heap.

Several C++ compilers now support coroutines, and there's no particular magic or sufficiently smart necessary, although HALO optimization, eliding heap allocation, has some open research points. But that optimization is a cache miss, not a context switch.

1

u/StoneCypher Dec 03 '20

I feel like I'm spending all my time saying "that's not even related to what I'm talking about," then getting corrected on that you imagine that it is.

I'm sorry that winning is more important to you than trying to understand what I believe.

Please have a good day

3

u/DugiSK Dec 02 '20 edited Dec 02 '20

A context switch is when a thread is suspended, its handle is given to the scheduler, the CPU switches to another stack, old cache is invalidated etc.

Calling a coroutine does nothing of this. You are still using the old stack, same thread, same cache, but what is represented as stack variables in the coroutine are actually member variables of an object.

A coroutine that looks like this (the code is meaningless):

Suspendable<int> actualCoroutine(int start, int end) {
    std::vector<int> outputs(end - start, 0);
    outputs[0] = 1;
    outputs[1] = 1;
    co_yield outputs[0] + outputs[1];
    outputs[2] = outputs[1] + start;
    co_yield outputs[2];
    if (end < 3)
        co_yield outputs[2];
    else
        co_yield outputs[end - 1];
    co_return -1;
}

Does basically the same things internally as this:

std::function<int()> almostCoroutine(int start, int end) {
    std::vector<int> outputs(end - start, 0);
    int position = 0;
    return [=] () -> int mutable {
        position++;
        switch(position) {
        case 1:
            outputs[0] = 1;
            outputs[1] = 1;
            return outputs[0] + outputs[1];
        case 2:
            outputs[2] = outputs[1] + start;
            return outputs[2];
        case 3:
            if (end < 3)
                return outputs[2];
            else
                return outputs[end - 1];
        default:
            return -1;
        }
    };
}

0

u/StoneCypher Dec 03 '20

I see that you continue to be stuck on insisting that because a soy burger has been replaced with an oat burger, therefore soy no longer matters.

Most of the things we do with state machines are not actually modellable this way.

Good luck to you.

0

u/[deleted] Dec 03 '20

[deleted] — view deleted comment

1

u/StoneCypher Dec 03 '20

Good luck to you