---
title: Superloops and cooperative scheduling
heading: Several jobs on one processor, each taking turns
eyebrow: C12 · Lesson 37 · Superloops and cooperative scheduling
xp: 40
---

::: hook
A real device does several things at once: blinks a status light, samples a sensor, answers a serial port, runs a control loop. A single processor does one thing at a time, so the program has to share it out. The simplest way, and the one most small firmware uses, is the **superloop**: an endless loop that offers each job, a **task**, a turn, where every task does a little work and returns quickly. As long as no task hogs its turn, they all appear to run together. It only takes one task that waits inside itself to break the illusion for everyone.
:::

::: play
- Three tasks share the loop: P0 toggles every 250 ms, P1 every 100 ms, and a status line goes to the terminal every 500 ms. Each task runs only when its next due time has come, then returns.
- On the timeline, P0 and P1 keep perfect time, interleaved.
- Set `BLOCKING` to 1: the status task now also does 150 ms of slow work in its turn. Run it and look at P1: whenever the status task runs, P1's toggles are delayed, and their spacing goes ragged.
:::
:::

```sim board
lang: c
attach: led P0 | red
attach: led P1 | green
attach: terminal
scope: P0, P1, TX
run: 2 s
code:
#include "board.h"

#define BLOCKING 0

uint32_t now_ms(void) { return SYS_CYCLES / 10000; }

void putc(char c) { while (UART_STATUS & UART_TX_FULL) ; UART_DATA = c; }

void blink_red(void)   { GPIO_TOGGLE = 1 << 0; }
void blink_green(void) { GPIO_TOGGLE = 1 << 1; }
void status(void) {
    const char *s = "status ok\n";
    while (*s) putc(*s++);
    if (BLOCKING) {                       // 150 ms of slow work, all at once
        uint32_t t = now_ms();
        while (now_ms() - t < 150) ;
    }
}

struct task { void (*run)(void); uint32_t period, next; };
struct task tasks[3] = {
    {blink_red, 250, 0}, {blink_green, 100, 0}, {status, 500, 0},
};

int main(void) {
    UART_BAUDDIV = 87;
    GPIO_DIR = (1 << 0) | (1 << 1);
    while (1) {                           // the superloop
        for (int i = 0; i < 3; i++) {
            if ((int32_t)(now_ms() - tasks[i].next) >= 0) {
                tasks[i].next += tasks[i].period;
                tasks[i].run();
            }
        }
    }
}
```

::: predict
## In a superloop, one task can take up to 20 ms per turn and never gives the processor up early. How late can another task's turn be?

- [ ] No later than 1 ms
- [x] Up to about 20 ms
- [ ] Up to the slow task's period
- [ ] It's never late

::: reveal
Up to about 20 ms: in a cooperative system no task can take the processor back from another, so a task whose turn comes while the slow one is running waits until it returns. The worst-case lateness of every task is set by the longest single turn of any other.
:::
:::

::: nameit
## The superloop

```c
while (1) {
    task_a();
    task_b();
    task_c();
}
```

Each task does a short piece of work and returns, keeping whatever it needs to remember between turns in its own state (often a state machine, lesson 36). Time-triggered versions, like the play's, run each task only when its period has passed, keeping a **next due time** per task; comparing with a signed difference, `(int32_t)(now - next) >= 0`, survives the clock wrapping.

## Rules

- **Never block:** no delay loops, no waiting for a slow device. Start the operation, return, and check on it next turn.
- The worst-case delay for any task is about the longest single turn of all the others, plus one pass of the loop.
- Urgent events go to interrupts, which pre-empt the loop; the ISR records the event and the task handles it.

## Utilization

A task taking $C_i$ every $T_i$ uses $C_i/T_i$ of the processor; the total

$$U = \sum_i \frac{C_i}{T_i}$$

must stay below 1, with margin for interrupts and lateness.

## Beyond the superloop

A **real-time operating system** (RTOS) gives each task its own stack and switches between them **pre-emptively**, by priority, on a timer interrupt: a slow low-priority task can no longer delay an urgent one. The price is memory for each task's stack, context-switch time, and new hazards, such as two tasks sharing data, which need mutexes.
:::

::: example
## Three tasks run 0.5 ms every 10 ms, 2 ms every 50 ms and 20 ms every 500 ms. What's the utilization?

::: solution
1. **Add each task's share.**
   $$\begin{aligned} U &= \frac{0.5}{10} + \frac{2}{50} + \frac{20}{500} \\ &= 0.05 + 0.04 + 0.04 \\ &= 0.13 \end{aligned}$$
   13% of the processor, leaving plenty of room.
2. **Check the long task.** The 20 ms task can delay the 10 ms task's turn by 20 ms, two whole periods, so it should be split into 1 ms pieces.

**Answer:** 13%, though the 20 ms task should be split into 1 ms pieces.
:::
:::

::: example
## How can the 150 ms of slow work in the play be done without blocking?

::: solution
1. **Split the work.** Each turn of `status` does 1 ms of work and returns.
2. **Remember progress.** A counter (a tiny state machine) records how far it got between turns.
3. **The result.** The work still takes 150 ms in total, spread over 150 turns, and the other tasks run between the pieces.

**Answer:** do it in 1 ms pieces, one per turn of `status`, with a counter recording how far it got.
:::
:::

::: example
## A superloop runs three tasks in turn, taking at most 0.5 ms, 2 ms and 20 ms. What is the worst-case wait for a task to get its next turn?

::: solution
1. **The worst case.** The task has just finished and must wait for the other two at their longest.
2. **For the first task.**
   $$2 + 20 = 22\ \text{ms}$$
3. **What it means.** One long task sets the response time of all the others, which is why long work is split into slices or moved to an interrupt.

**Answer:** 22 ms for the first task.
:::
:::

::: check
given: c1 = 0.2 | 1; t1 = 5 | 10; c2 = 3 | 10; t2 = 100 | 250
answer: 100*(c1/t1 + c2/t2)
unit: %
tolerance: 0.5%

## Task 1 takes {c1} ms every {t1} ms; task 2 takes {c2} ms every {t2} ms. What's the processor's utilization?

::: right
Right. $\sum C_i/T_i$ = {answer}%.
:::

::: misses
- [any] Not yet. Add each task's share, run time over period.
:::
:::

::: check
given: a = 0.5 | 2; b = 8 | 30 | 150
answer: (a + b + abs(a - b))/2
unit: ms
tolerance: 0

## In a superloop, task A's turns take up to {a} ms and task B's up to {b} ms. How late can each task's turn start, at worst, because of the other? Give the larger of the two.

::: right
Right. {answer} ms: one task can be kept waiting for the other's whole turn.
:::

::: misses
- [any] Not yet. Each can wait for the other's longest turn.
:::
:::

::: check
given: T = 10 | 25 | 100; s = 1 | 10 | 60
answer: s*1000/T
tolerance: 0.5%

## A task runs every {T} ms. How many times does it run in {s} seconds?

::: right
Right. {answer} times.
:::

::: misses
- [any] Not yet. Seconds over the period.
:::
:::

::: check
given: W = 60 | 150; p = 1 | 2 | 5
answer: W/p
tolerance: 0.5%

## A task's {W} ms of work is split into pieces of {p} ms, one per turn. How many turns does it take?

::: right
Right. {answer} turns, and no other task waits more than {p} ms for it.
:::

::: misses
- [any] Not yet. Work over piece size.
:::
:::

::: check
given: n = 4294967290 | 4294967000; T = 10 | 500
answer: n + T - 4294967296
tolerance: 0

## A task's next due time is {n} ms on a 32-bit clock, and its period is {T} ms. After `next += period`, what does `next` hold?

::: right
Right. {answer}: it wraps past $2^{32}$, and the signed difference with the clock still works.
:::

::: misses
- [n + T] A 32-bit unsigned value wraps at $2^{32}$.
- [any] Not yet. Add, then subtract $2^{32}$.
:::
:::

::: check
kind: choice

## A superloop task needs to wait 50 ms for a sensor to finish a measurement. What should it do?

- [ ] Call a 50 ms delay inside the task
- [x] Start the measurement, record the time, return, and on later turns check whether 50 ms have passed
- [ ] Disable interrupts for 50 ms
- [ ] Move all the other tasks into the sensor task

::: misses
- [1] That blocks every other task for 50 ms.
- [3] That would also stop the interrupts the other tasks rely on.
- [4] That's the same blocking with more code.
:::
:::

::: check
kind: c
given: A = 50 | 125 | 200; B = 30 | 70
attach: led P0; led P1
run: 1.5
expect: period(P0) = 2*A ms ± 1%; period(P1) = 2*B ms ± 1%

## Toggle P0 every `A` ms ({A}) and P1 every `B` ms ({B}) from one superloop, without blocking either.

```c starter
#include "board.h"

void wait_ms(uint32_t ms) { uint32_t t = SYS_CYCLES; while (SYS_CYCLES - t < ms * 10000) ; }

int main(void) {
    GPIO_DIR = 3;
    while (1) {
        GPIO_TOGGLE = 1; wait_ms(A);
        GPIO_TOGGLE = 2; wait_ms(B);
    }
}
```

```c solution
#include "board.h"

uint32_t now_ms(void) { return SYS_CYCLES / 10000; }

int main(void) {
    GPIO_DIR = 3;
    uint32_t next_a = 0, next_b = 0;
    while (1) {
        uint32_t now = now_ms();
        if ((int32_t)(now - next_a) >= 0) { next_a += A; GPIO_TOGGLE = 1; }
        if ((int32_t)(now - next_b) >= 0) { next_b += B; GPIO_TOGGLE = 2; }
    }
}
```

::: right
Right. Each task has its own due time, so neither waits for the other.
:::
:::

::: check
kind: micropython
given: A = 100 | 150; B = 40 | 60
attach: led P0; led P1
run: 1.5
expect: period(P0) = 2*A ms ± 2%; period(P1) = 2*B ms ± 2%

## The same in MicroPython: toggle P0 every {A} ms and P1 every {B} ms from one loop.

```micropython starter
from machine import Pin
import time

p0 = Pin(0, Pin.OUT)
p1 = Pin(1, Pin.OUT)
while True:
    p0.toggle()
    time.sleep_ms(A)
    p1.toggle()
    time.sleep_ms(B)
```

```micropython solution
from machine import Pin
import time

p0 = Pin(0, Pin.OUT)
p1 = Pin(1, Pin.OUT)
next0 = next1 = time.ticks_ms()
while True:
    now = time.ticks_ms()
    if time.ticks_diff(now, next0) >= 0:
        next0 = time.ticks_add(next0, A)
        p0.toggle()
    if time.ticks_diff(now, next1) >= 0:
        next1 = time.ticks_add(next1, B)
        p1.toggle()
    time.sleep_ms(1)
```

::: right
Right. The short sleep saves power and keeps both tasks within a millisecond of their times.
:::
:::

::: check
kind: parts
given: c1 = 0.5 | 1; t1 = 5 | 10; c2 = 2 | 4; t2 = 20 | 50; c3 = 5 | 20; t3 = 100 | 500

## Three tasks run {c1} ms every {t1} ms, {c2} ms every {t2} ms and {c3} ms every {t3} ms.

::: part
answer: (c1/t1 + c2/t2 + c3/t3)*100
unit: %
tolerance: 0.5%

### What is the processor's utilization?

::: misses
- [any] $\sum C_i/T_i$.
:::
:::

::: part
answer: c2 + c3
unit: ms
tolerance: 0.5%

### In a round-robin superloop, what's the longest the first task can wait for its turn?

::: misses
- [any] The other two at their longest.
:::
:::
:::

::: check
kind: parts
given: W = 50 | 150 | 600; s = 5 | 10 | 25

## {W} ms of slow work is split into slices of {s} ms so other tasks can run between them.

::: part
answer: ceil(W/s)
tolerance: 0

### How many slices?

::: misses
- [any] Total ÷ slice, rounded up.
:::
:::

::: part
answer: s
unit: ms
tolerance: 0.5%

### What is the longest it now holds the processor at once?

::: misses
- [any] One slice.
:::
:::
:::

::: explain
## Why does one blocking task ruin the timing of every other task in a superloop?

::: model
In a cooperative superloop, a task gives up the processor only by returning. While a task sits in a delay loop or waits for a slow device, the loop can't move on, so every other task's due time passes unnoticed and they all run late, by up to the blocking task's whole wait. Their lateness also varies with where in the blocking task's turn their due time fell, so their timing goes ragged. Splitting slow work into short pieces, or starting an operation and checking on it in later turns, keeps every turn short and bounds everyone's lateness to the longest short turn.
:::
:::

::: practice

::: check
given: c1 = 0.5 | 2; t1 = 10 | 20; c2 = 5 | 15; t2 = 200 | 500
answer: 100*(c1/t1 + c2/t2)
unit: %
tolerance: 0.5%

## Utilization of ({c1} ms every {t1} ms) and ({c2} ms every {t2} ms)?

::: misses
- [any] $\sum C_i/T_i$.
:::
:::

::: check
given: T = 20 | 40; s = 5 | 30
answer: s*1000/T
tolerance: 0.5%

## Runs of a {T} ms task in {s} s?

::: misses
- [any] s / T.
:::
:::

::: check
given: W = 90 | 400; p = 3 | 4
answer: W/p
tolerance: 0.5%

## Turns for {W} ms of work in {p} ms pieces?

::: misses
- [any] W / p.
:::
:::
:::
