Real-Time Operating Systems
An RTOS promises that each task finishes within a known worst-case time, every time. It gives up average speed to get that promise, which is why it runs brakes, pacemakers and spacecraft rather than desktops.
Predictable, Not Fast
A real time operating system is one whose timing can be guaranteed. If a task must react within 5 ms, an RTOS lets you prove it reacts within 5 ms on the worst day: every interrupt firing at once, caches cold, all tasks ready together. A desktop kernel is faster on average and still unfit for an airbag, because the airbag needs the worst case, not the average.
So the numbers that matter are bounds. The worst-case execution time (WCET) is the longest a piece of code can take. Interrupt latency is the time from a hardware signal to the first instruction of its handler, and scheduling latency is the time until the task that should run actually runs. Jitter is how much these vary. An RTOS keeps all of them small and, above all, known.
That rules out anything whose timing cannot be bounded on a time-critical path: demand paging (a page fault can wait on a disk), garbage collection, general-purpose memory allocation, and loops with no fixed limit.
- Worst-case response time, not throughput, is the measure
- WCET, interrupt latency, scheduling latency and jitter must be bounded
- No paging, unbounded loops or unpredictable allocation on critical paths
Hard, Firm and Soft Real Time Systems
Hard and soft real time systems differ in what a missed deadline costs. In a hard system it is a failure, as bad as a wrong answer: anti-lock brakes, pacemakers, flight controls. The design must show that no deadline is ever missed. In a soft system lateness only lowers quality: a dropped video frame, a late audio packet. Firm real time sits between: a late result is useless and thrown away, but nothing breaks, like a camera frame on a production line that arrives after the part has moved on.
The class decides what the system does when it runs late. A hard system must not; a firm system drops the work; a soft system carries on with lower quality.
| Hard | Firm | Soft | |
|---|---|---|---|
| A missed deadline | System failure | Result discarded | Lower quality |
| Examples | Brakes, pacemaker, flight control | Production-line vision, trading | Video, audio, games |
| Design goal | Prove no miss, ever | Keep misses rare | Keep average delay low |
- Hard: lateness is failure
- Firm: lateness makes the result worthless
- Soft: lateness makes the result worse
How an RTOS Schedules Tasks
Most RTOS kernels use preemptive fixed-priority scheduling: each task has a priority, and the moment a higher-priority task becomes ready it takes the CPU, even from the middle of another task. The designer picks the priorities. Rate monotonic ranks by period and deadline monotonic scheduling by deadline, and response time analysis then proves each task meets its deadline.
The alternative is to rank jobs by their deadlines at run time, which is earliest deadline first scheduling. It fits more work onto the CPU, up to 100%, but handles overload worse, so certified systems mostly stay with fixed priorities. Both are covered with one shared task set in those lessons.
To keep latency bounded, the kernel itself is small and preemptible: interrupt handlers do the minimum and hand the rest to a task, every system call has a known worst-case cost, and the scheduler picks the next task in constant time, often with a bitmap of ready priorities.
- Preemptive priority: the most important ready task always runs
- Priorities chosen offline and checked by analysis
- Short interrupt handlers and constant-time scheduling
The Pathfinder bug: priority inversion, then the fix
TASKS = {"H": (3, 1, 2, True), "M": (2, 2, 4, False), "L": (1, 0, 3, True)} # priority, arrives, work, uses the lock
H_DEADLINE = 6
def run(inherit):
left = {n: t[2] for n, t in TASKS.items()}
owner, timeline, done = None, "", {}
for now in range(20):
ready = [n for n, t in TASKS.items() if t[1] <= now and left[n] > 0]
if not ready:
break
# a lock user cannot run while someone else holds the lock
runnable = [n for n in ready if not (TASKS[n][3] and owner not in (None, n))]
def priority(n):
p = TASKS[n][0]
if inherit and n == owner: # holder borrows the priority of anyone it blocks
p = max([p] + [TASKS[w][0] for w in ready if w not in runnable])
return p
n = max(runnable, key=priority)
if TASKS[n][3]:
owner = n
left[n] -= 1
timeline += n
if left[n] == 0:
done[n] = now + 1
if owner == n:
owner = None
return timeline, done["H"]
for inherit in (False, True):
timeline, h = run(inherit)
verdict = "met" if h <= H_DEADLINE else "missed"
label = "with inheritance: " if inherit else "without inheritance:"
print(f"{label} {timeline} H done at t={h}, deadline {H_DEADLINE}: {verdict}")#include <algorithm>
#include <cstdio>
#include <string>
struct Task { char name; int priority, arrives, work; bool usesLock; };
const Task TASKS[] = {{'H', 3, 1, 2, true}, {'M', 2, 2, 4, false}, {'L', 1, 0, 3, true}};
const int H_DEADLINE = 6;
int run(bool inherit, std::string& timeline) {
int left[3], doneH = -1, owner = -1;
for (int i = 0; i < 3; i++) left[i] = TASKS[i].work;
for (int now = 0; now < 20; now++) {
bool ready[3], runnable[3], any = false;
for (int i = 0; i < 3; i++) {
ready[i] = TASKS[i].arrives <= now && left[i] > 0;
// a lock user cannot run while someone else holds the lock
runnable[i] = ready[i] && !(TASKS[i].usesLock && owner != -1 && owner != i);
any = any || ready[i];
}
if (!any) break;
int best = -1, bestP = -1;
for (int i = 0; i < 3; i++) {
if (!runnable[i]) continue;
int p = TASKS[i].priority;
if (inherit && i == owner) // holder borrows the priority of anyone it blocks
for (int w = 0; w < 3; w++) if (ready[w] && !runnable[w]) p = std::max(p, TASKS[w].priority);
if (p > bestP) { best = i; bestP = p; }
}
if (TASKS[best].usesLock) owner = best;
left[best]--;
timeline += TASKS[best].name;
if (left[best] == 0) {
if (best == 0) doneH = now + 1;
if (owner == best) owner = -1;
}
}
return doneH;
}
int main() {
for (bool inherit : {false, true}) {
std::string timeline;
int h = run(inherit, timeline);
std::printf("%s %s H done at t=%d, deadline %d: %s\n", inherit ? "with inheritance: " : "without inheritance:",
timeline.c_str(), h, H_DEADLINE, h <= H_DEADLINE ? "met" : "missed");
}
}public class Main {
static final char[] NAME = {'H', 'M', 'L'};
static final int[] PRIORITY = {3, 2, 1}, ARRIVES = {1, 2, 0}, WORK = {2, 4, 3};
static final boolean[] USES_LOCK = {true, false, true};
static final int H_DEADLINE = 6;
static int run(boolean inherit, StringBuilder timeline) {
int[] left = WORK.clone();
int owner = -1, doneH = -1;
for (int now = 0; now < 20; now++) {
boolean[] ready = new boolean[3], runnable = new boolean[3];
boolean any = false;
for (int i = 0; i < 3; i++) {
ready[i] = ARRIVES[i] <= now && left[i] > 0;
// a lock user cannot run while someone else holds the lock
runnable[i] = ready[i] && !(USES_LOCK[i] && owner != -1 && owner != i);
any |= ready[i];
}
if (!any) break;
int best = -1, bestP = -1;
for (int i = 0; i < 3; i++) {
if (!runnable[i]) continue;
int p = PRIORITY[i];
if (inherit && i == owner) // holder borrows the priority of anyone it blocks
for (int w = 0; w < 3; w++) if (ready[w] && !runnable[w]) p = Math.max(p, PRIORITY[w]);
if (p > bestP) { best = i; bestP = p; }
}
if (USES_LOCK[best]) owner = best;
left[best]--;
timeline.append(NAME[best]);
if (left[best] == 0) {
if (best == 0) doneH = now + 1;
if (owner == best) owner = -1;
}
}
return doneH;
}
public static void main(String[] args) {
for (boolean inherit : new boolean[]{false, true}) {
StringBuilder timeline = new StringBuilder();
int h = run(inherit, timeline);
System.out.printf("%s %s H done at t=%d, deadline %d: %s%n", inherit ? "with inheritance: " : "without inheritance:",
timeline, h, H_DEADLINE, h <= H_DEADLINE ? "met" : "missed");
}
}
}Step through it
Running on H (prio 3, lock 2 ticks, due 6) · M (prio 2, 4 ticks) · L (prio 1, lock 3 ticks)
Priority Inversion and the Pathfinder Bug
Locks are the classic trap. If a high-priority task waits for a lock held by a low-priority task, and a medium-priority task then preempts the low one, the high-priority task ends up waiting for the medium one. The wait is no longer limited by the short critical section; it lasts as long as unrelated work keeps running. Priority scheduling covers inversion and its fixes in general; here is why it matters so much in an RTOS.
In July 1997 the Mars Pathfinder lander, running VxWorks, began resetting itself on Mars. A high-priority bus task was blocked on a lock held by a low-priority weather task, while a medium-priority communications task ran. A watchdog saw the bus task miss its deadline and reset the spacecraft. Engineers reproduced it on a copy on Earth and uploaded a fix that turned on priority inheritance for that lock.
Under inheritance, the lock holder temporarily runs at the priority of the highest task waiting for it, so the medium task cannot get in between. Under a priority ceiling, the holder is raised to the highest priority of any task that uses the lock as soon as it takes it. Either way the wait is bounded by one critical section, which is what the timing analysis needs. The tracer replays the bug tick by tick.
- The danger is not the wait but its missing upper limit
- Inheritance: boost the holder when someone waits
- Ceiling: boost the holder as soon as it takes the lock
RTOS vs General-Purpose OS
A general-purpose OS such as Windows or desktop Linux aims for high throughput, fairness and rich features: virtual memory with paging, many drivers, file systems, a GUI. An RTOS aims for bounded timing and a small footprint. Many RTOS kernels fit in a few kilobytes of memory, run on microcontrollers with no memory management unit, and link straight into the application as one program.
The gains are predictable timing, fast start-up and low resource use. The costs are fewer services, more design work (priorities, stack sizes and timing must be worked out by hand), and less protection between tasks when there is no MMU. See types of operating systems for where real-time systems sit among the others.
- Advantages: bounded latency, small size, quick start
- Disadvantages: fewer services, harder design, often no memory protection
Real Time Operating System Examples
Common examples: FreeRTOS, maintained by Amazon under the MIT licence, is the usual choice on small microcontrollers such as the ESP32. Zephyr, a Linux Foundation project, targets small connected devices. VxWorks runs in spacecraft, including Pathfinder and later Mars rovers, and in avionics. QNX, a microkernel RTOS, is common in car infotainment and driver-assistance units. RTEMS is used in many space missions.
Linux itself gained real-time support when the PREEMPT_RT work was merged into the mainline kernel in 2024 (version 6.12). It makes most of the kernel preemptible and gives latencies of tens of microseconds, which suits many industrial and audio systems. It is generally treated as soft or firm real time; hard real-time systems that need certification still use a dedicated RTOS.
- FreeRTOS and Zephyr: microcontrollers and IoT
- VxWorks, RTEMS: spacecraft and avionics
- QNX: cars
- Linux with PREEMPT_RT: soft and firm real time