It is virtually a rite of passage for C programmers to realize that they can write their own cooperative multitasking system. C is low-level enough, and there are several ways to approach the problem, so, like Jedi light sabers, each one is a little bit different. [Christoph Wolcher] took his turn, and not only is his system an elegant hack, if that’s not an oxymoron, it is also extremely well documented.
Before you dig in, be warned. [Christoph] fully admits that you should use an RTOS. Or Rust. Besides, after he finished, he discovered the protothreads library, which does a similar task in a different way that is both more cool and more terrible all at the same time.
Once you dig in, though, you’ll see the system relies on state machines. Just to prove the point, he writes a basic implementation, which is fine, but hard to parse and modify. Then he shows a simple implementation using FreeRTOS, which is fine except for, you know, needing FreeRTOS.
Using a simple set of macros, it is possible to get something very similar to the RTOS version that runs independently, like the original version. Most of the long code snippets show you what code the macros generate. The real code is short and to the point.
Multiprocessing is a big topic. You can have processes, threads, fibers, and coroutines. Each has its pros and cons, and each has its place in your toolbox.