---
title: Preemptive scheduling
heading: Tasks, priorities, response times and priority inversion
eyebrow: C12 · Lesson 38 · Preemptive scheduling
xp: 40
---

::: hook
A superloop gives every task its turn in order, so one slow task delays all the others. A **real-time operating system** (RTOS) instead runs the highest-priority task that's ready, interrupting a lower one the moment something more urgent can run. That makes response times independent of slow background work, but it brings two new problems: proving that every task meets its deadline when they all compete, and sharing data safely between tasks that can interrupt each other. Both have exact answers, and one of them nearly lost a spacecraft.
:::

::: play
- Three tasks run under fixed priorities: task 1 (C₁ ms every 4 ms), task 2 (C₂ ms every 6 ms) and task 3 (C₃ ms, lowest priority).
- The staircase is the work that must be done before task 3 can finish if it starts with everyone: its own C₃ plus every release of the higher tasks so far. The diagonal is the time available.
- Task 3's **response time** is where the staircase first touches or dips below the diagonal. Raise C₃ or C₂ and watch that point move out, or vanish when the processor is overloaded.
:::

```sim plot
view: graph
x: t = 0..40 ms
y: w = 0..40 ms
slider: C1 = 0.5..2 step 0.5 = 1 ms
slider: C2 = 0.5..3 step 0.5 = 2 ms
slider: C3 = 1..10 step 0.5 = 3 ms
samples: 2000
plot: C3 + ceil(t/4)*C1 + ceil(t/6)*C2 | label: work due by t
plot: t | dashed | label: time available
readout: utilization of tasks 1 and 2 (%) = (C1/4 + C2/6)*100 | digits: 3
```

::: predict
## A high-priority task needs a mutex that a low-priority task holds for 1 ms. A medium-priority task, which doesn't use the mutex, becomes ready and runs for 20 ms. How long can the high-priority task wait?

- [ ] 1 ms
- [x] About 21 ms
- [ ] 20 ms
- [ ] It can't be blocked, because it has the highest priority

::: reveal
The medium task preempts the low one while it holds the mutex, so the high task waits for the medium task's whole 20 ms and then the low task's 1 ms: **priority inversion**. With **priority inheritance**, the low task runs at the high task's priority while it holds the mutex, so the medium task can't preempt it and the wait is 1 ms. The Mars Pathfinder lander kept resetting in 1997 from exactly this; turning on inheritance in its RTOS fixed it.
:::
:::

::: nameit
## Preemption

Each task has a priority. The scheduler runs the highest-priority **ready** task; a task that waits (for a timer, a queue, a semaphore) stops being ready. Switching tasks saves one task's registers and restores another's: a **context switch**, typically a few hundred cycles. Each task needs its own stack.

## Response-time analysis

With **rate-monotonic** priorities (shorter period, higher priority), task $i$'s worst-case response time satisfies
$$R_i = C_i + \sum_{j\ \text{higher}} \left\lceil \frac{R_i}{T_j}\right\rceil C_j$$
Solve it by iteration, starting from $R = C_i + \sum C_j$, until it stops changing. The task meets its deadline if $R_i \le D_i$. The utilization bound $n(2^{1/n} - 1)$ from the real-time lesson is sufficient, not necessary: a set over the bound may still pass this exact test.

## Sharing data

A **mutex** protects data shared between tasks; only its holder may touch the data. A task blocked on a mutex can suffer **priority inversion**, bounded by **priority inheritance** (the holder borrows the waiter's priority). Interrupt handlers can't block, so they hand work to tasks through **queues** and **semaphores**, which never make the ISR wait.
:::

::: example
## Tasks of 1 ms every 4 ms, 2 ms every 6 ms and 3 ms every 13 ms run rate-monotonically. Do they meet their deadlines (deadline = period)?

::: solution
1. **Task 1.** It has the highest priority, so R = 1 ms.
2. **Task 2.** Start at 3:
   $$2 + \lceil 3/4\rceil \times 1 = 3$$
   so R = 3 ms.
3. **Task 3.** Start at 6 and iterate until R stops changing:
   $$\begin{aligned} 3 + 2 \times 1 + 1 \times 2 &= 7 \\ 3 + 2 + 2 \times 2 &= 9 \\ 3 + 3 + 4 &= 10 \\ 3 + \lceil 10/4\rceil + 2\lceil 10/6\rceil &= 10 \end{aligned}$$
   R = 10 ms, within 13.
4. **Compare with the utilization bound.** All pass, although the utilization is over the three-task bound of 78.0%:
   $$\frac14 + \frac26 + \frac{3}{13} = 81.4\%$$

**Answer:** yes: the response times are 1, 3 and 10 ms, all within their periods.
:::
:::

::: example
## A 1 kHz tick costs 50 cycles, and the system makes 2000 context switches a second at 200 cycles each. What share of the 10 MHz processor is overhead?

::: solution
1. **Overhead cycles as a share of the clock.**
   $$\begin{aligned} &\frac{1000 \times 50 + 2000 \times 200}{10^7} \\ &= 4.5\% \end{aligned}$$
2. **Where it goes.** Most of it is switching; a design that wakes tasks only when there's work, rather than polling every tick, cuts it.

**Answer:** 4.5% of the processor.
:::
:::

::: example
## Six tasks each get a 512-byte stack on a chip with 16 KB of RAM. What does that cost, and what does it mean for the stack-painting test?

::: solution
1. **Total stack.**
   $$6 \times 512 = 3072\ \text{bytes}$$
   3 KB, about 19% of the RAM, before any data.
2. **What each stack must hold.** Each task's stack must hold its own deepest call chain plus an interrupt frame.
3. **Paint each one.** So each is painted and checked separately; most RTOSes can report every task's high-water mark.

**Answer:** 3 KB, about 19% of the RAM, and each task's stack is painted and checked separately.
:::
:::

::: check
kind: parts
given: C1 = 2 | 3; T1 = 5 | 6; C2 = 5 | 7

## Task 1 runs {C1} ms every {T1} ms at high priority; task 2 needs {C2} ms at lower priority.

::: part
answer: C2 + ceil((C2 + ceil((C2 + ceil((C2 + C1)/T1)*C1)/T1)*C1)/T1)*C1
unit: ms
tolerance: 0

### What is task 2's worst-case response time?

::: misses
- [C2 + C1] Task 1 may be released again while task 2 is still running: iterate.
- [any] $R = C_2 + \lceil R/T_1\rceil C_1$, iterated.
:::
:::

::: part
answer: C1/T1*100
unit: %
tolerance: 0.5%

### What share of the processor does task 1 take?

::: misses
- [any] $C_1/T_1$.
:::
:::
:::

::: check
kind: parts
given: C1 = 1 | 2; T1 = 4 | 10; C2 = 2 | 5; T2 = 8 | 20; C3 = 3 | 6; T3 = 15 | 50

## Three tasks: {C1} ms every {T1} ms, {C2} ms every {T2} ms, {C3} ms every {T3} ms.

::: part
answer: (C1/T1 + C2/T2 + C3/T3)*100
unit: %
tolerance: 0.5%

### What is their total utilization?

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

::: part
answer: step(3*(2^(1/3) - 1) - (C1/T1 + C2/T2 + C3/T3))
tolerance: 0

### Is it under the three-task bound of 78.0% (1 for yes)?

::: misses
- [any] Compare with $3(2^{1/3} - 1)$.
:::
:::
:::

::: check
kind: parts
given: c = 0.5 | 1 | 2; m = 5 | 20 | 50

## A high-priority task waits for a mutex held for {c} ms by a low-priority task; a medium-priority task can run for {m} ms.

::: part
answer: c + m
unit: ms
tolerance: 0.5%

### How long can it wait without priority inheritance?

::: misses
- [c] The medium task can preempt the mutex's holder.
- [any] Critical section plus the medium task.
:::
:::

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

### And with it?

::: misses
- [any] Only the critical section.
:::
:::
:::

::: check
kind: parts
given: k = 100 | 1000; t = 30 | 80; s = 500 | 5000; w = 150 | 400

## A {k} Hz tick costs {t} cycles, and {s} context switches a second cost {w} cycles each, on the 10 MHz board.

::: part
answer: (k*t + s*w)/1e7*100
unit: %
tolerance: 0.5%

### What share of the processor is overhead?

::: misses
- [any] Total cycles per second ÷ $10^7$.
:::
:::

::: part
answer: w/10
unit: µs
tolerance: 0.5%

### How long is one context switch?

::: misses
- [any] Cycles ÷ 10 MHz.
:::
:::
:::

::: check
kind: parts
given: n = 4 | 6 | 10; s = 256 | 512 | 1024; R = 8 | 16 | 32

## {n} tasks get {s}-byte stacks on a chip with {R} KB of RAM.

::: part
answer: n*s
unit: bytes
tolerance: 0

### How much RAM do the stacks take?

::: misses
- [any] Tasks × stack size.
:::
:::

::: part
answer: n*s/(R*1024)*100
unit: %
tolerance: 0.5%

### What share of RAM is that?

::: misses
- [any] Over $R \times 1024$.
:::
:::
:::

::: check
kind: match

## Match each need to the RTOS tool for it.

- An ISR must wake a task when a byte arrives :: a semaphore or queue the ISR gives without waiting
- Two tasks update the same structure :: a mutex with priority inheritance
- A task must run every 10 ms exactly :: a periodic delay to an absolute wake-up time
- A sensor task passes readings to a logging task :: a queue
- [extra] disabling the scheduler for the whole program

::: misses
- [any] An ISR can't wait; tasks that share data lock it; periodic tasks wait for absolute times.
:::
:::

::: check
kind: choice

## Why must an interrupt handler never wait on a mutex?

- [ ] Mutexes are too slow
- [x] An ISR isn't a task: it can't be suspended, so waiting would stop everything below it, possibly forever if the holder can't run
- [ ] An ISR always has the lowest priority
- [ ] It would cause priority inheritance

::: misses
- [1] Speed isn't the issue; blocking is.
- [3] Interrupts preempt every task.
- [4] Inheritance applies between tasks.
:::
:::

::: check
kind: python

## Write `response_times(tasks)`: `tasks` is a list of (C, T) pairs in priority order, highest first. Return each task's worst-case response time by iterating $R = C_i + \sum_j \lceil R/T_j\rceil C_j$ over the higher tasks, or `None` for a task whose R exceeds its period T.

```python starter
import math

def response_times(tasks):
    return []
```

```python solution
import math

def response_times(tasks):
    out = []
    for i, (c, t) in enumerate(tasks):
        r = c + sum(cj for cj, _ in tasks[:i])
        while True:
            nxt = c + sum(math.ceil(r / tj) * cj for cj, tj in tasks[:i])
            if nxt > t:
                r = None
                break
            if nxt == r:
                break
            r = nxt
        out.append(r)
    return out
```

```python tests
assert response_times([(1, 4), (2, 6), (3, 13)]) == [1, 3, 10], "The worked example: 1, 3 and 10 ms."
assert response_times([(1, 4), (2, 6), (3, 9)]) == [1, 3, None], "With a 9 ms period, task 3 misses."
assert response_times([(2, 5), (4, 10)]) == [2, 8], "4 + 2 × 2 = 8."
assert response_times([(5, 5)]) == [5], "A single task alone."
```

::: right
Right. This is the test real schedulers are checked with; it's exact for fixed priorities when tasks don't block each other.
:::
:::

::: explain
## How does priority inheritance prevent a medium-priority task from delaying a high-priority one indefinitely?

::: model
The trouble starts when a low-priority task holds a mutex that a high-priority task needs. The high task blocks, and any medium-priority task that becomes ready can preempt the low one, which then can't finish its critical section and release the mutex, so the high task waits for as long as the medium tasks keep running. With priority inheritance, the low task temporarily takes on the high task's priority while it holds the mutex. Medium tasks can no longer preempt it, so it finishes the critical section quickly and releases the mutex, and the high task's wait is bounded by the length of that critical section.
:::
:::

::: practice
::: check
given: C1 = 1 | 2; T1 = 5 | 10; C2 = 2 | 4
answer: C2 + ceil((C2 + ceil((C2 + ceil((C2 + C1)/T1)*C1)/T1)*C1)/T1)*C1
unit: ms
tolerance: 0

## Response time of a {C2} ms task under a {C1} ms task every {T1} ms?

::: misses
- [any] Iterate $R = C_2 + \lceil R/T_1\rceil C_1$.
:::
:::

::: check
given: c = 1 | 3; m = 10 | 40
answer: c + m
unit: ms
tolerance: 0.5%

## Worst wait without inheritance: {c} ms critical section, {m} ms medium task?

::: misses
- [any] Both add.
:::
:::

::: check
given: n = 3 | 5 | 8
answer: n*(2^(1/n) - 1)*100
unit: %
tolerance: 0.5%

## Rate-monotonic bound for {n} tasks?

::: misses
- [any] $n(2^{1/n} - 1)$.
:::
:::
:::
