23б. Stackless coroutines (protothreads): waiting as a plain line of code with switch and LINE
Section 23а turned every wait into a state of a machine and a timer event. That is
reliable, but the code breaks into pieces: "start a conversion, wait 30 ms, wait for
the flag, read" becomes three states and a transition table. There is a technique that
gives back the linear form with no kernel and no separate stack per task: a function
remembers the line where it stopped, and on the next call a switch jumps straight to
it. The result is a stackless coroutine — in C, with standard means, two bytes of state each.
Grounds: alg.c was built with gcc 12.2.0 on a computer (stm-sys:1) and run by
host.c — four coroutines of a device for three seconds of model time, a second time
with a time counter that wraps past 2³². The same alg.c was built with
arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F, Cortex-M3 and Cortex-M0 —
function sizes and stack frames. bad.c reproduces the two main traps of the technique.
Terms used in the documentation
Term Meaning protothread a stackless coroutine built from C macros stackless coroutine a coroutine that keeps no stack of its own between calls local continuation the resume point: a line number in the lcfieldDuff's device a caselabel inside a loop: the trick everything rests onresume point the place where the function continues child protothread, spawn a child coroutine and starting it while waiting for its end implicit fallthrough falling into the next caselabel withoutbreakduplicate case value two identical caselabels — a compile errorIn plain words. A coroutine is a function with a bookmark. Call it — it gets to the place where it must wait, puts the bookmark there and returns. Call it again — it opens at the bookmark and checks whether it may go on. It has no stack of its own, so everything that must survive a wait lives not in local variables but in its structure.
23б.1 The idea: waiting right in the code, but without a stack
A FreeRTOS task (section 26) is written linearly: vTaskDelay(30) — and the next line
runs 30 ms later. For that the kernel saves all registers and keeps a separate stack for
every task. The state machine of 23а gets by with one common stack, but its waiting is a
transition to another state, and the linear form is lost.
A stackless coroutine takes the best of both: it is written linearly and lives on the common stack. The price is rules: you may wait only in the body of the coroutine itself (not in a nested function), local variables do not survive a wait, and the turn is only given up voluntarily. At heart it is the same state machine: the line number is the state number, only the preprocessor writes the transition table for you.
23б.2 Macros: switch, LINE and a case label in the middle of a loop
The whole state of a coroutine is one field:
typedef struct {
uint16_t lc; /* номер строки, с которой продолжить; 0 — с начала */
} pt_t;
PT_BEGIN opens a switch on this field, PT_END closes it and resets the bookmark:
#define PT_BEGIN(pt) switch ((pt)->lc) { case 0:
#define PT_END(pt) } (pt)->lc = 0; return PT_ENDED
A wait puts its own line number into lc and places a case label on that same line.
On the next call the switch jumps straight to that label — even if it is inside a for,
a while or an if branch: C allows a case label to stand in any nested statement of
the switch body. It is the same trick as in the famous unrolled copy loop — "Duff's device".
#define PT_WAIT_UNTIL(pt, cond) \
do { \
(pt)->lc = __LINE__; \
__attribute__((fallthrough)); \
case __LINE__: \
if (!(cond)) \
return PT_WAITING; \
} while (0)
The line __attribute__((fallthrough)); is only there so that gcc with -Wextra does
not warn about falling into the next label: here it is intended. Giving up the turn
unconditionally is the same, but the return stands before the label:
#define PT_YIELD(pt) \
do { \
(pt)->lc = __LINE__; \
return PT_YIELDED; \
case __LINE__:; \
} while (0)
The line number is 16-bit: that is enough for a file of up to 65535 lines, and the structure stays at two bytes.
23б.3 Time: a deadline by difference
Waiting for time is an ordinary condition. The coroutine remembers the start and the length, and "the deadline has passed" is a difference of unsigned numbers, as with the software timers of 23а.4:
static inline bool tm_done(const ptimer_t *t, uint32_t now)
{
return (uint32_t)(now - t->start) >= t->len;
}
Subtraction modulo 2³² does not break when the millisecond counter wraps through zero (49.7 days after power-on); the experiment in 23б.7 checks this.
23б.4 🔧 Blinking and a button with debouncing
Blinking is an endless loop with a wait inside, exactly as it is written on an RTOS:
int blink_run(blink_t *b, uint32_t now)
{
PT_BEGIN(&b->pt);
for (;;) {
tm_set(&b->t, now, 500);
PT_WAIT_UNTIL(&b->pt, tm_done(&b->t, now));
b->led = !b->led;
b->toggles++;
}
PT_END(&b->pt);
}
The button: a press counts if the level has held for 20 ms; anything shorter is bounce or noise. After a press we wait for the release and 20 ms more, so that the release bounce does not become a new press:
PT_WAIT_UNTIL(&k->pt, raw);
tm_set(&k->t, now, 20);
PT_WAIT_UNTIL(&k->pt, !raw || tm_done(&k->t, now));
if (!raw) {
k->rejected++; /* дребезг или помеха короче 20 мс */
continue;
}
k->presses++;
PT_WAIT_UNTIL(&k->pt, !raw);
On the state machine of 23а this is four states and a table; here it is eight lines top
to bottom. continue inside a coroutine works as usual: it belongs to the for, not to
the switch.
23б.5 A sensor: a deadline, a ready flag and yielding
The sensor is started, converts for 30 ms, and then may still not be ready — so the coroutine checks the flag on every pass, giving the turn to the others:
*start = true;
tm_set(&s->t, now, 30);
PT_WAIT_UNTIL(&s->pt, tm_done(&s->t, now));
while (!*ready) {
s->extra_polls++;
PT_YIELD(&s->pt);
}
s->sum += *value;
s->reads++;
PT_WAIT_UNTIL(&s->pt, tm_done(&s->period, now));
The period is a separate timer set at the start of the loop: measurements go once per 1000 ms from the start, not 1000 ms after the read, and the conversion time does not accumulate into drift.
23б.6 A child coroutine: a report over UART
You may wait only in the body of the coroutine itself — an ordinary function called from it cannot wait. So a repeated part with waiting is made a child coroutine with its own structure, and the parent waits for its end. Sending a string byte by byte is the classic example:
int tx_run(tx_t *c, volatile bool *tx_empty, volatile uint8_t *dr)
{
PT_BEGIN(&c->pt);
while (c->n) {
PT_WAIT_UNTIL(&c->pt, *tx_empty);
*tx_empty = false;
*dr = *c->p++;
c->n--;
}
PT_END(&c->pt);
}
The byte counter n and the pointer p live in the structure: local variables do not
live between waits (23б.10). The parent starts the child from the beginning and waits
until it returns PT_ENDED:
#define PT_SPAWN(pt, child, call) \
do { \
PT_INIT(child); \
PT_WAIT_UNTIL(pt, (call) == PT_ENDED); \
} while (0)
PT_SPAWN(&r->pt, &r->tx.pt, tx_run(&r->tx, tx_empty, dr));
23б.7 Experiment: three seconds on a computer and wrapping past 2³²
host.c spins a loop of 3000 passes of 1 ms. On every pass it updates the peripheral
model and calls all four coroutines once — that is the whole "scheduler". The button is
pressed from 400 to 900 ms with 6 ms of bounce on press and release, 5 ms of noise at
1500 ms, the second press from 2000 to 2300 ms. The sensor is ready 33 ms after being
started, the UART accepts the next byte after 2 ms.
| What was measured | value |
|---|---|
| coroutine calls | 12000 |
| LED toggles | 5 |
| presses counted | 2 |
| short pulses rejected (bounce and noise) | 4 |
| sensor measurements | 3 |
| extra polls of the ready flag | 12 |
| bytes sent to the UART | 12 |
Exactly S1, S2, S3 with a line break went to the UART — three reports of four bytes.
Of the four rejected pulses three are the bounce of the first press, the fourth is the
noise; the release bounce was never counted. Extra polls — four per measurement: the
30 ms deadline passes before the sensor is ready (33 ms plus one more pass on which the
model sees the start), and the coroutine gives these passes to the others through PT_YIELD.
The second run started with the time counter at 0xFFFFFF00: after 256 ms it wraps
through zero. All seven numbers matched the first run — a deadline by difference does
not notice the wrap.
The memory of all four is just their structures:
| Coroutine | context bytes | what it waits for |
|---|---|---|
blink_t |
20 | a 500 ms deadline |
button_t |
20 | the button level and a 20 ms deadline |
sensor_t |
32 | a 30 ms deadline, the ready flag, a 1000 ms period |
report_t (with tx_t) |
40 | a new measurement, an empty UART register |
112 bytes in all, of them 2 bytes each for the bookmarks. An RTOS task has, on top of its structure, a stack of its own; the device of 23а on the kernel took about 2.4 KB of RAM (23а.7).
23б.8 What the compiler produces: sizes and frames
gcc turns a switch on line numbers into a chain of comparisons or a jump table — as
with an ordinary state machine. Code sizes (bytes) and stack frames at -O2:
| Function | Cortex-M4F | Cortex-M3 | Cortex-M0 | M4F frame | M0 frame |
|---|---|---|---|---|---|
blink_run |
56 | 58 | 60 | 0 | 0 |
button_run |
136 | 132 | 122 | 4 | 8 |
sensor_run |
132 | 162 | 128 | 8 | 12 |
tx_run |
94 | 94 | 64 | 4 | 8 |
report_run |
144 | 184 | 144 | 8 | 24 |
Frames are 0 to 8 bytes on Cortex-M4F: a wait holds no stack, the function returns every
time. gcc inlined tx_run right into report_run — there is no separate call there. On
Cortex-M0 report_run calls __aeabi_uidivmod: M0 has no divide instruction, and
sent % 10 needs one; hence the 24-byte frame.
23б.9 Coroutines, the state machines of 23а or an RTOS
- Coroutines — when the logic is sequential at heart: "start, wait, check, repeat", exchange protocols, start-up scripts. The code reads top to bottom, memory is tens of bytes.
- A state machine with a table (23а) — when there are many events and the reaction depends on the "state × event" combination: menus, device modes. A table is checked by eye; a coroutine has none.
- An RTOS (section 24) — when preemptive multitasking is needed: a long computation must not delay the reaction to a button, and waiting has to happen inside library functions. A coroutine will not interrupt a long calculation: until it returns, the others stand still.
The techniques combine: coroutines spin in the superloop of 23а, and events from interrupts reach them through the same queue. Sleeping between passes — as in 23а.6 and 84.6.
23б.10 Pitfalls
A local variable across a wait. A loop counter i inside a coroutine starts anew on
every call. In bad.c a three-step loop with PT_YIELD made 19 steps in 20 calls and
never finished — it should have finished on the fourth call. Everything that survives a
wait goes into the structure (like n and p of tx_t).
A wait inside a nested switch. The case __LINE__ label goes to the inner switch;
the outer one does not see it. In bad.c such a coroutine skipped to the end on the next
call and returned PT_ENDED: in five calls it "finished" twice and never waited out its
condition, although on the fourth call it was true. gcc with -Wall -Wextra gave not a
single warning. Inside a coroutine — if instead of switch.
Two waits on one line. Both labels get the same __LINE__:
PT_WAIT_UNTIL(pt, a); PT_WAIT_UNTIL(pt, b);
gcc answers duplicate case value — at least this error is visible at once.
A wait in a nested function. return PT_WAITING from an ordinary function returns
control to that function itself, not to the scheduler. The waiting part goes into a child
coroutine (23б.6).
A long calculation without yielding. A coroutine that computes for 50 ms without
PT_YIELD stops the button and the UART for the same 50 ms. That needs a preemptive task —
which is section 24.
23б.11 Summary
- A stackless coroutine is a function with a bookmark: a line number in the
lcfield, and theswitchjumps to thecase __LINE__label even inside a loop. State — 2 bytes, the stack is shared. PT_WAIT_UNTIL— a bookmark and a condition check;PT_YIELD— give up the turn once;PT_SPAWN— wait for a child coroutine.- Waiting for time is a condition with a deadline by difference: the experiment with a counter wrapped past 2³² gave the same numbers.
- Four coroutines of a device over 3000 ms: 5 toggles, 2 presses, 4 rejected pulses, 3 measurements, 12 bytes to the UART; contexts — 112 bytes, frames — 0 to 8 bytes on Cortex-M4F.
- Rules: local variables do not survive a wait, you may not wait in a nested
switchor a nested function, two waits go on different lines. - Sequential logic — coroutines, "state × event" — the state machine of 23а, long calculations and preemption — an RTOS.
Check yourself
- What does a stackless coroutine keep between calls? - A) All processor registers - B) The line number to continue from and the fields of its structure - C) Its whole stack - D) Nothing: it starts from the beginning every time
- Why can't a loop counter be kept in a local variable of a coroutine?
- A) Local variables are forbidden in a
switch- B) The compiler puts them into Flash - C) The function returns at every wait, and on the next call the variable is created anew - D) Local variables are slower than structure fields - What happens if a wait is placed inside a nested
switch? - A) The label goes to the innerswitch, and on the next call the coroutine skips to the end - B) A compile error - C) Nothing, everything works - D) The processor falls into HardFault
Check yourself: answers
- 1 — B. Why: The lc bookmark and the context structure are its whole state; the stack is shared (23б.2).
- 2 — C. Why: In the bad.c experiment a three-step loop never finished in 20 calls (23б.10).
- 3 — A. Why: The outer switch does not see the label, the coroutine returns PT_ENDED, and gcc stays silent (23б.10).
Next: section 24 "How FreeRTOS is organized" — which files the kernel consists of, how its types and functions are named and what it takes for it to start on a board.