3 ms·
Don't miss out on the brilliant link at the bottom - Adam Dunkels' Protothreads - Lightweight, Stackless Threads in C also uses nested switch/case statements [1
by j1elo 6y ago
Don't miss out on the brilliant link at the bottom - Adam Dunkels' Protothreads - Lightweight, Stackless Threads in C also uses nested switch/case statements [1].
I learned about the theory with it, and used his library to implement cooperative multitasking on a bare metal embedded AVR C project. I wrote a task manager and dispatcher based on Protothreads, and that effort was what later made it simple for me to understand the JS async/await paradigm that would appear under my radar a couple years later.
EDIT to add that I think the concepts might still apply, since these days I've seen things like stackless async coroutines discussed for Rust... didn't study those in detail yet, but I wouldn't be surprised if the basic concepts are the same.
[1]: Current website: http://dunkels.com/adam/pt/ http://dunkels.com/adam/pt/
- sillysaurusx 6y agoWikipedia entry on protothreads: https://en.wikipedia.org/wiki/Coroutine#Implementations_for_C https://en.wikipedia.org/wiki/Coroutine#Implementations_for_... The source code is interesting. LC_SET is particularly neat: /* WARNING! lc implementation using switch() does not work if an LC_SET() is done within another switch() statement! */ /** \hideinitializer */ typedef unsigned short lc_t; #define LC_INIT(s) s = 0; #define LC_RESUME(s) switch(s) { case 0: #define LC_SET(s) s = __LINE__; case __LINE__: #define LC_END(s) }
- edflsafoiewq 6y agoOne cool thing you can do is to manage the numbers in the case manually, eg. #define LC_SET(s,num) s = num; case num: This will let you serialize the state s, modify the program, recompile and reload s, and have it resume at the desired point.
- exDM69 6y agoYou could take this one step further by using the __COUNTER__ macro to generate unique numbers in the preprocessor. Alas, this isn't a part of the standard (iirc), so you need to depend on compiler-specific features.
- edflsafoiewq 6y agoWhat I'm thinking of is modifying it like this LC_SET(s,0) A + LC_SET(s,2) + C LC_SET(s,1) B When the number for each resume point is explicit instead of automatic, you can edit the source code while controling where any existing suspended coroutines will resume at.
- photojosh 6y agoWe use Protothreads in our commercial embedded product to handle a complicated communication protocol to a time-of-flight sensor chip over I2C. It works quite well, but since every function in the call stack needs to pass the protothreads variable it becomes rather complicated.
- SV_BubbleTime 6y agoWhy not an RTOS at that point? Is FreeRTOS too heavy in your application?