Hacking Coroutines into C 12.7.2025 A while ago, I was part of a team developing embedded software. The software was deeply rooted in state machines - dozens of them—spread across multiple functions. While this architecture is common in embedded development, especially for systems without an operating system, I started to question: Is this really the clearest way to express control flow? The state machines in our code worked fine, but understanding and maintaining them was often a headache. They lacked a linear flow, requiring mental juggling of flags, states, and transitions scattered across polling functions. I kept thinking: Wouldn't this be easier if we could just write the logic like a sequential program—waiting for events and resuming where we left off? Of course, the project didn’t allow us to use an RTOS. So, the conventional approach of using threads or blocking system calls to manage concurrency was off the table. Yet, I knew there had to be a middle ground. Around that time, I had been using coroutines in languages like Python, JavaScript, Dart, and Rust. They allow you to pause and resume execution without relying on threads—offering a kind of cooperative multitasking. It hit me: this coroutine pattern could be the perfect fit for our problem—providing concurrency without requiring an OS. Before diving into a coroutine-based solution, let’s take a step back and look at a small toy example that illustrates the problem. We want to implement an LED blinker with a user-controllable period, denoted as $p$. Initially, the LED blinks with a fixed period of 2 seconds. However, the user should be able to change this period at any time by pressing and holding a button. When the button is released, the LED should restart its blinking cycle with a new period equal to twice the duration the button was held ($p/2$). To model this behavior, we can use two simple state machines, as shown in the following figure: The first state machine, led_blinker, consists of two stat...
First seen: 2025-07-13 01:52
Last seen: 2025-07-13 07:53