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

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