Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท RTOS and Scheduling

Building a Cooperative Scheduler

Build a simple cooperative scheduler for microcontrollers in C: periodic run-to-completion tasks, jitter from long tasks, and protothread-style non-blocking waits.

Between a single super loop and a full preemptive RTOS lies a very useful middle ground: the cooperative scheduler. Tasks are ordinary functions that run to completion and return; the scheduler calls each one when it is due. Nothing ever interrupts a task except a hardware interrupt, so there are no context switches, no per-task stacks and almost no locking problems. A few dozen lines of C give you clean separation between jobs, and it runs on the smallest microcontrollers.

This lesson builds one from scratch, shows its main weakness (a long task delays everything), and then introduces protothreads, a trick that lets a task "wait" without blocking.

The idea: run to completion

In a cooperative system each task is a function that does a short piece of work and returns. The scheduler, running inside main(), repeatedly checks which tasks are due and calls them. Because only one task runs at a time and only returns voluntarily, two tasks can never be in the middle of modifying the same data. (Interrupts can still interrupt tasks, so shared data with an ISR still needs care.)

flowchart TD
    A["Timer ISR: now_ms++"] --> B
    B["main loop: for each task in table"] --> C{"now - last >= period?"}
    C -- yes --> D["call task function (runs to completion)"]
    D --> E["last += period"]
    E --> B
    C -- no --> B

The scheduler is just a loop over a table.

A task table gives each job a function, a period and the time of its last run. This is easy to read, easy to extend, and needs no dynamic memory.

A table-driven scheduler

The program below simulates time in milliseconds. Each task function does its work and "spends" some simulated time, as real code would. The scheduler checks the table in order, so earlier entries effectively have higher priority when several tasks are due at once. The output shows when each task actually started and how late it was.

C A table-driven cooperative scheduler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You will see the blink task start late whenever sensor or ui was running when it fell due. This is jitter, and in a cooperative system the worst-case jitter of any task equals the longest run time of all the others. That gives a design rule: no task may run longer than the shortest deadline in the system. If a 12 ms task shares a scheduler with a task that needs 5 ms precision, you must split the long task into steps or move to a preemptive RTOS.

Also notice t->last += t->period_ms instead of last = now: as in the software timers lesson, the release times stay on a fixed grid, so lateness does not accumulate as drift.

Breaking a long job into steps

The standard cure for long tasks is a state machine: remember where you are in a static variable, do a small slice, return, and continue at the next call. A 40 ms sensor read becomes ten 4 ms slices (start conversion, return; check result, return; read bytes, return). The code is no longer linear, which is awkward for anything with many steps.

Protothreads: non-blocking waits in linear code

A protothread (popularized by Adam Dunkels' Contiki project) lets you write a task in the natural, top-to-bottom style, with a "wait until" statement that returns to the scheduler if the condition is false and resumes at the same line next time. It is built from nothing but a switch statement and the __LINE__ macro: the task stores its current line number, and on re-entry the switch jumps right back to that case.

C Protothread-style tasks with switch and __LINE__

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Each task looks like a thread that blocks on events, yet there is only one stack and no context switch: a blocked task simply returns, and switch jumps back to its line later. There are two famous limits: local variables do not survive between calls (hence static in the examples, or fields in a struct), and you cannot put a PT_WAIT_UNTIL inside a switch statement of your own. For these reasons, protothreads are best for small, event-driven control logic.

Newer C and C++ offer other approaches (C++20 coroutines, Rust async), and some embedded runtimes build state machine frameworks on the same idea.

Strengths and limits

Strengths:

  • Tiny and predictable: a few hundred bytes, one stack, no kernel.
  • No race conditions between tasks, so no mutexes between them.
  • Easy to understand and to test on a PC, as these simulations show.

Limits:

  • A misbehaving task (an endless loop, a blocking delay_ms()) freezes the whole system.
  • No priorities beyond table order, and response time is bounded by the longest task.
  • Long computations need to be chopped into pieces.
  • Fault isolation is nonexistent: one bug is everyone's bug.

If you meet deadlines of a few milliseconds with long background jobs such as flash writes or encryption, add a preemptive RTOS (see what is an RTOS) or run the urgent work in an interrupt. Many products mix both: a cooperative loop for ordinary work and ISRs for what is urgent.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a cooperative scheduler, what bounds the worst-case delay before a task can start?

    A task can only start when the running task returns, so a long task delays everything.
  2. 2. Why does the scheduler use 'last += period' instead of 'last = now'?

    Adding the period keeps the average rate exact, even if a release was a little late.
  3. 3. What is the main trick that makes protothreads possible in plain C?

    The task saves the line number of its wait and the switch jumps back to that case on the next call.
  4. 4. Which is NOT an advantage of a cooperative scheduler?

    A cooperative scheduler cannot preempt a running task; only interrupts can.

Summary

  • A cooperative scheduler calls run-to-completion task functions from a table when their period has elapsed.
  • Worst-case jitter equals the longest-running task, so keep every task shorter than the tightest deadline.
  • Long jobs become state machines, or protothreads that resume at a saved __LINE__.
  • It is tiny and race-free between tasks, but has no preemption, so one stuck task freezes the system.

Next: RTOS Synchronization