Learn how an RTOS works
Watch a real-time kernel make every scheduling decision, next to the source code that makes it. The simulator below runs line-by-line models of FreeRTOS and Zephyr, checked against the real kernels. Press play, or step through it.
Shown: priority inheritance (mutex). A low-priority task holds a mutex that a high-priority task needs. Read the lesson, or try every scenario in the playground.
Basics
What an RTOS is, and the ideas every other lesson builds on. Start here if real-time kernels are new to you.
- What is an RTOS?What "real-time" really means, what a real-time kernel gives a program, and how an RTOS differs from Linux and from bare-metal code.
- Main loop vs RTOSWhy a bare-metal main loop answers an urgent event only as fast as one pass of the loop, and how an RTOS kernel answers it at once.
- Tasks and stacksWhat a task is made of (a function, a stack of its own and a control block), why every task needs its own stack, and how to size one.
- Task statesRunning, ready, delayed, blocked, suspended and ended, followed through one task's life, with the names each kernel uses for them.
Concepts
What a real-time kernel does, on any RTOS. Each lesson runs on the kernels you can switch between.
- How an RTOS scheduler decides what runsTask states, the ready list, the tick and the idle task, shown on two tasks that take turns sleeping.
- PreemptionHow a kernel takes the CPU from a running task the moment a more urgent one becomes ready.
- Time slicingHow tasks of equal priority share the CPU, and why the first slice in Zephyr is one tick longer.
- Semaphores as signalsHow one task waits for another with a binary semaphore, why the waiter runs the moment it is signalled, and how a semaphore differs from a mutex.
- Priority inversionHow a medium-priority task can keep a high-priority task waiting for a lock it has nothing to do with.
- Priority inheritanceHow a mutex bounds priority inversion by lending the waiter's priority to the task that holds the lock.
- Nested mutexes and when an inherited priority dropsA task that holds two mutexes inherits a priority through one of them. FreeRTOS keeps it until both are released; Zephyr drops it as soon as nobody waits.
- Waiting for a mutex with a timeoutWhat happens when a task stops waiting for a mutex, and how each kernel takes back the priority the holder inherited from it.
- Mutex handoff: who gets a mutex when it is unlockedFreeRTOS frees the mutex and lets tasks compete for it; Zephyr gives it straight to the most urgent waiter. One program, two outcomes.
- DeadlockTwo tasks, two mutexes, taken in opposite order. Why neither kernel notices, and how to design it away.
- Interrupts and deferred handlingWhy an interrupt handler should only signal a task, how the task runs the moment the interrupt returns, and what happens to interrupts that arrive while it is busy.
- Periodic tasks and deadlinesWhy a delay in a loop drifts and a sleep until the next period does not, what a deadline is, and how a more urgent task makes a periodic one miss it.
- Counting semaphoresA semaphore that counts higher than 1, used as a pool of identical resources or to count events, and why a task waiting for one inherits nothing.
- Queues between tasksHow a message queue passes data from a producer to a consumer, what happens when it is full or empty, and what its length buys you.
- Queue handoff: who gets an item sent to a waiting taskZephyr copies an item straight to the task waiting for it; FreeRTOS puts it in the queue and lets the woken task try again. One program, two outcomes.
- Software timersHow a software timer runs a callback after a delay or every period, and why FreeRTOS runs it in a task of its own while Zephyr runs it in the tick interrupt.
- Event groupsHow a task waits for several events at once, all of them or any one, how one set of bits wakes every task it satisfies, and what each kernel returns to the waiter.
FreeRTOS
How FreeRTOS does it, in its own source code.
- The tick and vTaskDelay in FreeRTOSHow vTaskDelay puts a task in a delayed list and how xTaskIncrementTick wakes it, line by line in the FreeRTOS source.
- The context switch in FreeRTOSHow FreeRTOS on a Cortex-M3 saves one task's registers, picks the next task and restores its registers, in the PendSV handler.
- How FreeRTOS chooses the next taskvTaskSwitchContext, the search through the ready lists and the walking index that makes tasks of one priority take turns, in the FreeRTOS source.
- Tick count overflow in FreeRTOSHow FreeRTOS keeps delays working when its 32-bit tick count wraps round to zero, with two delayed lists that swap roles.
- Suspending, resuming and ending a task in FreeRTOSHow vTaskSuspend and vTaskResume move a task in and out of xSuspendedTaskList, how the kernel tells a suspended task from one that waits forever, and why a task that deletes itself is freed by the idle task.
- Priority inheritance in FreeRTOSHow xTaskPriorityInherit raises a mutex holder and xTaskPriorityDisinherit lowers it again, line by line in the real kernel source.
- Interrupts in FreeRTOSHow xSemaphoreGiveFromISR wakes a task without switching, how portYIELD_FROM_ISR asks for the switch, and what xYieldPending does when the handler does not ask.
- xTaskDelayUntil in FreeRTOSHow xTaskDelayUntil keeps a periodic task on a fixed grid of wake-up times, and what it does when the task overruns its period.
- Semaphores in FreeRTOSHow FreeRTOS builds a counting semaphore on its queue, how xQueueSemaphoreTake waits when the count is 0, and why a woken task takes the count itself when it runs.
- Queues in FreeRTOSHow xQueueSend and xQueueReceive copy items through a ring of slots, how a task waits for room or for an item, and why the queue is locked while it does.
- Software timers in FreeRTOSHow the timer service task keeps its list of active timers, sleeps until the next one is due, runs the callbacks and processes the commands that xTimerStart and xTimerStop send it.
- Event groups in FreeRTOSHow xEventGroupWaitBits stores what a task waits for in its own list item, how xEventGroupSetBits walks every waiting task with the scheduler suspended, and why an interrupt's setBits goes through the timer service task.
- Task notifications in FreeRTOSHow a task notification signals a task directly, without a semaphore, how the count tells the task how many signals it got, and what Zephyr offers instead.
Zephyr
How Zephyr does it, in its own source code.
- The tick and k_sleep in ZephyrHow k_sleep puts a thread on Zephyr's timeout list, why it wakes one tick later than asked, and how the tick announcement wakes it, in the real kernel source.
- The context switch in ZephyrHow Zephyr decides that another thread should run, where it actually switches, and what arch_swap does on the native_sim board, in the real kernel source.
- How Zephyr chooses the next threadZephyr's run queue, next_up and the cache, and how a time slice moves a thread behind its equals, in the real kernel source.
- Cooperative threads in ZephyrA Zephyr thread with a negative priority is never preempted by another thread. How should_preempt decides it, and when cooperative threads are the right choice.
- Suspending, resuming and ending a thread in ZephyrHow k_thread_suspend and k_thread_resume set and clear one bit of a thread's state, why a suspended thread keeps its timeout, and how a thread whose entry function returns is halted at once.
- Priority inheritance in ZephyrHow k_mutex_lock raises a chain of mutex owners and k_mutex_unlock works the priority out again, in the real kernel source.
- Interrupts in ZephyrHow k_sem_give behaves in an interrupt handler, why it never switches threads there, and how the interrupt exit picks the thread to run.
- Periodic sleep in ZephyrHow k_sleep with an absolute timeout keeps a periodic thread on a fixed grid, why it gets no extra tick, and what happens when the end of the period has already passed.
- Semaphores in ZephyrHow k_sem_take and k_sem_give work on a count, a limit and a wait queue, why a give to a waiting thread never raises the count, and what happens to a give at the limit.
- Message queues in ZephyrHow k_msgq_put and k_msgq_get move messages through a ring buffer, and how the kernel finishes a waiting thread's call for it, so that a woken thread never has to try again.
- Timers in ZephyrHow a k_timer is a timeout in the same list as every sleeping thread, how its expiry function runs inside the tick interrupt, and how its period is kept from drifting.
- Events in ZephyrHow k_event_wait records what a thread waits for in the thread itself, how k_event_post walks the wait queue and hands each waiter the events that satisfied it, and what the _safe variants clear.
Glossary
The terms the lessons use.
- Context switchSaving the CPU state of one task and restoring that of another, so each task continues as if it had never stopped.
- Counting semaphoreA semaphore whose count can go above 1, for a pool of identical resources or for events that may arrive faster than they are handled.
- Critical sectionA short stretch of code during which interrupts are masked, so nothing else can run and change shared data halfway through.
- DeadlineThe time by which a job must be finished, counted from its release; why the kernel does not check it, and hard vs soft deadlines.
- Deferred interrupt handlingSplitting interrupt work into a short handler that signals and a task that does the rest, at a priority of the designer's choosing.
- Delayed listWhere FreeRTOS keeps sleeping tasks, sorted by wake-up tick, and what Zephyr uses instead.
- Event groupA set of event bits that tasks set, clear and wait for, waiting for all of a set of bits or for any one of them.
- Idle taskThe lowest-priority task every kernel creates, which runs whenever no application task is ready.
- Interrupt service routine (ISR)The function the CPU runs when a peripheral raises an interrupt, ahead of every task, and why it should be short.
- JitterHow much the start (or end) of a periodic job varies from one period to the next, and where it comes from in an RTOS.
- Message queueA kernel object that passes items of data between tasks, first in first out, blocking a receiver while it is empty and a sender while it is full.
- MutexA lock with an owner, used to give one task at a time access to a shared resource, and the kernel help that ownership makes possible.
- PendSVThe ARM Cortex-M exception that RTOS ports use to perform the context switch once every other interrupt has finished.
- PeriodThe fixed time between the starts of a periodic task's jobs, and why it is kept with a delay until a point in time, not a delay from now.
- PriorityThe number that tells the scheduler how urgent a task is, and why FreeRTOS and Zephyr count it in opposite directions.
- Producer and consumerThe pattern where one task makes items and another handles them, joined by a queue that absorbs the difference in their pace.
- Race conditionTwo tasks update the same data and one update is lost, because a task can be stopped between reading a value and writing it back.
- Rate-monotonic schedulingGiving periodic tasks priorities by period, shortest period most urgent, and the utilisation bound that tells you in advance when every deadline is met.
- Ready listThe kernel structure that holds the tasks able to run, organised so the most urgent one is found quickly.
- Run queueZephyr's structure of ready threads, a list sorted by priority with the next thread cached.
- Scheduler lockKeeping the running task on the CPU without masking interrupts, so it can work on shared data that only tasks use.
- SemaphoreA counter that tasks take and give, used to signal between tasks and to count resources, with no owner.
- Software timerA kernel service that calls a function after a delay (one-shot) or every period (auto-reload), without a task of its own.
- Stack overflowA task using more stack than it was given and overwriting the memory next to it, how each kernel detects it, and how the high-water mark helps size stacks.
- Task control block (TCB)The structure in which a kernel keeps everything it knows about one task, such as its saved stack pointer, priority and list links.
- Task notificationA FreeRTOS signal sent straight to one task, through a value each task has, without a semaphore or queue object in between.
- TickThe periodic timer interrupt that gives an RTOS kernel its sense of time, and the unit that delays and timeouts are counted in.
- Tickless idleStopping the periodic tick while nothing is due, so an idle CPU can sleep for longer, and how each kernel catches up on the time that passed.
- Time sliceThe share of CPU time a task gets before the kernel lets the next task of the same priority run.
- Timer service taskThe task FreeRTOS creates to run every software timer callback and to process the commands that start and stop timers. Also called the timer daemon.
- Wait queueThe list of tasks waiting for one kernel object, such as a mutex or semaphore, ordered by priority.
- Work queueA kernel thread that runs functions handed to it by interrupts and other threads, so deferred work needs no task of its own.
Playground
Every scenario from the lessons in one simulator, with every parameter open to change: open the scheduler playground.
Resource for learning RTOS
RTOS 101
- NASA: Real-Time Operating Systems (RTOS) 101
- Operating Systems: From 0 to 1 Bootstrap yourself to write an OS from scratch. A book for self-learner.
- Kernels 101 – Let’s write a Kernel
- RTOS vs. Bare Metal: Navigating Performance, Complexity, and Efficiency
- Real-Time Systems Concepts
- RTOS Fundamentals
- A Simple Scheduler via an Interrupt-driven Actor Model
- ARM Cortex-M RTOS Context Switching
Books
Courses
- RTOS (YouTube Playlist)
- Beyond the RTOS (YouTube Playlist)
- Modern Embedded Systems Programming Course
- Real-Time Bluetooth Networks - Shape the World
- An RTOS Based Software Development for Embedded Systems
- Development of Real-Time Systems
- astering RTOS: Hands on FreeRTOS and STM32Fx with Debugging
- Getting started with TI-RTOS training series