r/cpp • Game Developer | quiz.cpp-perf.com • Aug 10 '23

The downsides of C++ coroutines

https://reductor.dev/cpp/2023/08/10/the-downsides-of-coroutines.html
91 Upvotes

90 comments sorted by

View all comments

Show parent comments

7

u/14ned LLFIO & Outcome author | Committee WG14 Aug 11 '23

Duff's devices were the old fashioned goto for implementing as-if coroutines in C for a long time. I remember a C preprocessor macro based implementation of C++ coroutines which is nearly drop in semantically identical. It's implemented using a Duff's Device.

Here it is: https://github.com/jamboree/co2. I deployed it into production one place I worked, because C++ coroutines at the time were nearly unusable. It worked surprisingly well, it was easier to debug at that time than C++ coroutines too.

4

u/HeroicKatora Aug 11 '23 edited Aug 11 '23

Not seeing Duff's device anywhere in the macro output. Where is the arithemtic calculation of the label and loop? Are you calling all interleaving of case-labels in other scopes Duff's device? To me that's just the goto nature of switch. The surprising portion of Duff was taking that it step further by turning it into a calculated goto (that doesn't even require a jump target lookup-table). That labeling of yours just seems so strange to me. As if knowledge of some fundamental property of switch has been lost, and only survived in the hacks built on top.

The library is how state machines were implemented in machine languages before C, except those would have stored the label addresses and saved a lut. Which, if I understand the discussions, is a hope for C++ coroutine syntax, that this might be possible by having special semantics in the hidden switch. It's still not Duff's device. I'm intently curious as to what the motivation behind calling it that could be.

4

u/14ned LLFIO & Outcome author | Committee WG14 Aug 11 '23

The use of the term "Duff's Device" in relation to coroutines is long standing. For example:

You'll find more if you search an engine.

Is it exactly accurate given the original Duff's device? No.

Is it reasonable to describe any complex logic implemented using an atypical use of the switch statement? I'd say so.

I'd even say it could apply to any complex logic implemented using an atypical use of a jump table. Which is basically a state machine, so I get what you're saying here that it's an inaccurate use of the term.