Priority Inversion and Mutex Inheritance in FreeRTOS
Priority inversion is one of the sneakiest scheduling bugs in embedded systems: a high-priority task starts waiting on a low-priority one it should never have to wait for.
The scenario
Low-priority task L locks a resource. High-priority task H requests the same resource and blocks. Meanwhile medium-priority task M starts running and preempts L, so H effectively waits behind M.
The fix: priority inheritance
Mutexes created with xSemaphoreCreateMutex() in FreeRTOS support priority inheritance: task L holding the resource is temporarily raised to H's priority so it releases the resource quickly.
Binary semaphores (xSemaphoreCreateBinary) do not implement inheritance. Always use a mutex for mutual exclusion.Practical advice
- Keep critical sections as short as possible.
- Never take a mutex from an interrupt context.
- Visualise timing issues with Tracealyzer / SystemView.