3 ms·
Duff's device has been used for more than loop unrolling though. https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html https://www.chiark.greenend.org.u
by butterisgood 5y ago
Duff's device has been used for more than loop unrolling though.
https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
which inspired:
http://dunkels.com/adam/pt/ http://dunkels.com/adam/pt/
And that stuff is just neat!
- deleted 5y ago[deleted]
- wahern 5y agoI'm a prolific user of Duff's device for poor man's coroutines in C, but in non-toy applications I do try to isolate the behavior to discrete functional tasks and entirely behind a simple, conventional API. For example, implementing a single-function iterator using a generator pattern: https://github.com/wahern/lunix/blob/36c2107/src/unix-getopt.c#L45 https://github.com/wahern/lunix/blob/36c2107/src/unix-getopt... IOW, I avoid the urge to encapsulate the magic in a library abstraction so it can be reused (and abused) everywhere. There's no spooky action at a distance--you can figure out the behavior from the surrounding code, without having to pour through internal library code (even just hiding stuff in a header can be confusing). The details remain entirely irrelevant to callers. And I minimize opportunities for doing things I might regret (and have regretted), like implementing and relying upon a bespoke threading framework =)
- anitil 5y agoDoing arithmetic on __LINE__..... I'm mostly impressed and very slightly horrified. So of course I'll be stealing this.
- pwdisswordfish9 5y agoOn more than one occasion I wanted to write: switch (foo) { if (0) { case X: /* X-specific code */ } else { case Y: /* Y-specific code */ } /* common code for X and Y */ break; }
- ktpsns 5y agoThis is not much different to writing GOTOs directly, is it?
- sumtechguy 5y agoOne cool use I saw of it was in the instruction decoder for bochs. Duffs device is really nice for decoding instruction sets that are not necessarily regular in size (such as x86).
- photojosh 5y agoContext here is embedded: I wrote an entire I2C driver on AVR using protothreads. This was so I could just call a single update function in my main loop and it would handle all the various delays. Do not recommend. If I had my time again, I would do it with a explicit state machine that runs in the I2C interrupt handler, and a submission and response queue accessed by the main app loop (the equivalent of "userland" for non-embedded folks).