RTOS: priority inversion, and the mutex that fixes it
Three FreeRTOS tasks share a lock. With a binary semaphore the high-priority task waits behind a medium one; with a mutex, priority inheritance cuts the wait…
RTOS · Advanced
In a real product: Spacecraft and robot flight software (Aerospace and drones): Flight software shares buses between tasks of different priorities, where a late high-priority task can mean a reset.
Priority inversion is the bug that kept resetting NASA's Mars Pathfinder lander in 1997. A low-priority task holds a lock that a high-priority task needs. Then a medium-priority task, which needs no lock at all, preempts the low one and runs for as long as it likes. The high-priority task now waits for the medium one, though they share nothing.
This sketch sets up exactly that, every 600 ms, with three FreeRTOS tasks on an Uno. In odd cycles the lock is a binary semaphore, in even cycles a mutex, and the high task prints how long it waited each time. Three LEDs show which task is working.
What you'll learn
- How three priorities, one lock and bad timing give unbounded waiting
- Priority inheritance: while a task holds a FreeRTOS mutex that a higher one wants, it runs at that higher priority
- Why
xSemaphoreCreateMutex()andxSemaphoreCreateBinary()look alike but behave differently - Measuring a task's own CPU time, not the time that passes while it is preempted
How it works
The Uno's FreeRTOS port ticks about every 16 ms, from the watchdog timer. Each cycle starts at a tick:
- Low (priority 1) takes the lock and works for 60 ms of its own CPU time. Green LED.
- One tick later, high (priority 3) wakes and asks for the lock. It is taken, so high blocks.
- One tick after that, medium (priority 2) wakes and works for 250 ms. Yellow LED.
With a binary semaphore, medium outranks low, so low stops in the middle of its locked work and waits. High waits for low, which waits for medium: about 290 ms.
With a mutex, the moment high blocks on it, FreeRTOS raises low to priority 3. Medium can't preempt it. Low finishes its 60 ms, gives the mutex back (and drops to priority 1), and high runs at once: it waited about 30 ms. Medium runs after that.
work() counts only the time its task is really running. It adds up micros() in small steps and ignores any gap longer than 200 µs, which can only mean another task ran in between. So "60 ms of work" stays 60 ms even when the task is preempted.
Try this
- Make medium's work 500 ms. The semaphore wait grows with it, the mutex wait doesn't: that is "unbounded".
- Give low priority 3 too. Now there is no inversion: why?
- Watch the LEDs in the logic analyzer: with the semaphore, green stops in the middle while yellow runs.
sketch.ino
// Priority inversion on FreeRTOS: low takes a lock, high wants it, medium runs in between. Odd cycles use a binary
// semaphore (no priority inheritance), even cycles a mutex (with it); high prints how long it waited.
#include <Arduino_FreeRTOS.h>
#include <semphr.h>
const int LOW_LED = 10, MEDIUM_LED = 11, HIGH_LED = 12;
const TickType_t PERIOD = pdMS_TO_TICKS(600);
SemaphoreHandle_t semaphore, mutex;
volatile SemaphoreHandle_t lock;
volatile TickType_t cycleStart;
// Runs for ms of this task's own CPU time: gaps over 200 us are time other tasks ran, not counted.
void work(unsigned long ms, int led) {
digitalWrite(led, HIGH);
long left = ms * 1000L;
unsigned long t = micros();
while (left > 0) {
unsigned long now = micros(), d = now - t;
t = now;
if (d < 200) left -= d;
digitalWrite(led, HIGH); // back on after a preemption
}
digitalWrite(led, LOW);
}
// Each task waits out its offset first, then runs every PERIOD from there: low, then high a tick later, then medium.
void lowTask(void *) {
vTaskDelay(1);
TickType_t last = xTaskGetTickCount();
for (;;) {
vTaskDelayUntil(&last, PERIOD);
cycleStart = last;
xSemaphoreTake(lock, portMAX_DELAY);
work(60, LOW_LED);
xSemaphoreGive(lock);
}
}
void mediumTask(void *) {
vTaskDelay(3);
TickType_t last = xTaskGetTickCount();
for (;;) {
vTaskDelayUntil(&last, PERIOD);
work(250, MEDIUM_LED);
}
}
void highTask(void *) {
vTaskDelay(2);
TickType_t last = xTaskGetTickCount();
for (int cycle = 1;; cycle++) {
vTaskDelayUntil(&last, PERIOD);
TickType_t asked = xTaskGetTickCount();
xSemaphoreTake(lock, portMAX_DELAY);
TickType_t got = xTaskGetTickCount();
digitalWrite(HIGH_LED, HIGH);
xSemaphoreGive(lock);
Serial.print(F("cycle "));
Serial.print(cycle);
Serial.print(lock == mutex ? F(", mutex: ") : F(", binary semaphore: "));
Serial.print(F("high waited "));
Serial.print((got - asked) * portTICK_PERIOD_MS);
Serial.println(F(" ms"));
digitalWrite(HIGH_LED, LOW);
lock = lock == mutex ? semaphore : mutex; // the other kind next cycle (nobody holds either now)
}
}
void setup() {
Serial.begin(115200);
pinMode(LOW_LED, OUTPUT);
pinMode(MEDIUM_LED, OUTPUT);
pinMode(HIGH_LED, OUTPUT);
semaphore = xSemaphoreCreateBinary();
xSemaphoreGive(semaphore); // a binary semaphore starts empty: make it "free"
mutex = xSemaphoreCreateMutex();
lock = semaphore;
Serial.print(F("Tick: "));
Serial.print(portTICK_PERIOD_MS);
Serial.println(F(" ms"));
xTaskCreate(lowTask, "low", 100, NULL, 1, NULL);
xTaskCreate(mediumTask, "medium", 100, NULL, 2, NULL);
xTaskCreate(highTask, "high", 160, NULL, 3, NULL);
}
void loop() {}