FreeRTOS mutexes and waking a task from an ISR
About this lesson
Two FreeRTOS tasks on an ESP32 DevKit (Arduino-ESP32 core) share one Serial port, and their lines come out mixed. A mutex fixes that: one key, taken before the port is used and given back after, while a task that finds the key gone is Blocked and costs nothing. Then a button: its interrupt service routine must never wait, so it cannot touch the mutex. It gives a binary semaphore with xSemaphoreGiveFromISR(), and portYIELD_FROM_ISR() switches straight to the task that does the work. The general theory is in the OS lessons “Semaphores” and “Locks, spinlocks and atomic instructions”; the FromISR pattern for data was in “FreeRTOS queues: xQueueSend from tasks and ISRs”.
Two tasks, one Serial port
Task A prints temp= and then 21, in two calls. Task B prints pressed. If the scheduler runs B between A's two calls, you read temp=pressed, then 21. The port needs one user at a time.
shared resource one Serial port, two tasks
task A Serial.print("temp="); Serial.println(21);
task B Serial.println("pressed");
B runs between A's two calls:
> temp=pressed
> 21Read the lesson step by step
Two tasks, one Serial port
Task A prints temp= and then 21, in two calls. Task B prints pressed. If the scheduler runs B between A's two calls, you read temp=pressed, then 21. The port needs one user at a time.
shared resource one Serial port, two tasks task A Serial.print("temp="); Serial.println(21); task B Serial.println("pressed"); B runs between A's two calls: > temp=pressed > 21A mutex is a key
A mutex (short for mutual exclusion) works like a single key. xSemaphoreCreateMutex() makes one, and it starts free. The rule we keep: a task touches Serial only while it holds the key.
serialLock = xSemaphoreCreateMutex(); mutex one key, free at the start take get the key (or wait for it) give hand it back rule use Serial only while holding itTask A takes the key
Task A calls xSemaphoreTake(serialLock, portMAX_DELAY). The key is free, so the call returns at once with pdTRUE and A holds it. A prints temp=.
task A xSemaphoreTake(serialLock, portMAX_DELAY); key free -> returns pdTRUE at once Serial.print("temp="); > temp=Task B has to wait
B has the higher priority, so it can run in the middle of A's line. But its xSemaphoreTake finds the key gone, so B enters the Blocked state. A blocked task uses no processor time, so A carries on.
task B priority 2 > 1: runs in the middle of A's line xSemaphoreTake(serialLock, portMAX_DELAY); key held by A -> B is Blocked Blocked uses no processor time task A is the highest Ready task again: it carries on portMAX_DELAY wait as long as it takesA gives the key back
A prints 21 and calls xSemaphoreGive(serialLock). That unblocks B, which takes the key, prints pressed on its own line and gives it back. Whoever takes a mutex must give it back, soon.
task A Serial.println(21); xSemaphoreGive(serialLock); -> B unblocks task B gets the key, Serial.println("pressed"); xSemaphoreGive(serialLock); > temp=21 > pressedB waits on a semaphore
A binary semaphore holds 0 or 1. xSemaphoreCreateBinary() makes it empty: 0. B calls xSemaphoreTake(press, portMAX_DELAY) and blocks until something gives it. No polling, no wasted time.
press = xSemaphoreCreateBinary(); // starts at 0 task B xSemaphoreTake(press, portMAX_DELAY); 0 -> nothing to take -> Blocked no loop checking the button: B costs nothing while it waitsThe button starts the ISR
The button pulls the pin low. That falling edge starts onPress(), the interrupt service routine (ISR), at once, in the middle of whatever task is running. An ISR must never wait, so it may not use a mutex.
GPIO 4 HIGH -> LOW (falling edge) attachInterrupt(BUTTON, onPress, FALLING); the CPU stops task A between two instructions and runs onPress() an ISR must not block: mutexes are not allowed in ISRsThe ISR gives the semaphore
onPress() calls xSemaphoreGiveFromISR(press, &woke). The semaphore becomes 1 and B becomes Ready. B outranks A, the task that was interrupted, so the call sets woke to pdTRUE. No switch happens yet.
BaseType_t woke = pdFALSE; xSemaphoreGiveFromISR(press, &woke); press 0 -> 1 task B Blocked -> Ready priority 2 > 1 -> woke = pdTRUESwitch straight to B
portYIELD_FROM_ISR(woke) asks for a task switch as the ISR ends, so B runs next instead of waiting for the next tick. B takes press, back to 0, and prints pressed, with the mutex.
portYIELD_FROM_ISR(woke); // woke == pdTRUE -> switch ISR ends -> task B runs (not task A) task B xSemaphoreTake(press, ...) returns, press 1 -> 0 takes serialLock, Serial.println("pressed"), gives it backShort ISR, task does the work
This is deferred interrupt processing: the ISR only notes that the event happened, and a task does the slow work. Use a mutex to share something between tasks, and a semaphore given from an ISR to wake a task.
ISR a few lines: give, yield task the slow work, with mutexes if it needs them mutex tasks only, must be given back binary semaphore any giver, even an ISR (FromISR)
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Task A prints "temp=" and then 21 in two calls; task B prints "pressed". With no mutex, what can the Serial port show?
If the scheduler runs B between A's two calls, B's whole line lands in the middle of A's: temp=pressed, then 21.
02Task B calls xSemaphoreTake(serialLock, portMAX_DELAY) while task A holds the mutex. What happens to B?
With portMAX_DELAY (and INCLUDE_vTaskSuspend set to 1) B waits as long as it takes. A Blocked task uses no processor time, so A carries on and finishes its line.
03Why may an interrupt service routine not take or give a FreeRTOS mutex?
An ISR must never block, and a mutex's priority inheritance changes task priorities. The FreeRTOS reference says mutex type semaphores cannot be used from within interrupt service routines. ISRs use the FromISR functions instead.
04Task B (priority 2) is blocked on the binary semaphore press. Task A (priority 1) is running when the button's ISR calls xSemaphoreGiveFromISR(press, &woke). What is woke afterwards?
xSemaphoreGiveFromISR sets *pxHigherPriorityTaskWoken to pdTRUE when giving unblocked a task whose priority is higher than the currently running task, here B over A.
05What does portYIELD_FROM_ISR(woke) do when woke is pdTRUE?
Without the request, B would wait until the scheduler next runs, in the worst case the next tick. With it, the interrupt returns straight into B, which does the slow work while the ISR stays short.
Glossary
- Task
- One job in FreeRTOS, written as a function that loops forever. The scheduler gives the processor to the highest-priority task that is ready.
- Shared resource
- Something two or more tasks use, such as a Serial port or a buffer. Without a rule their uses can mix.
- Mutex
- Short for mutual exclusion: a single key for a shared resource. A task takes it before using the resource and must give it back after.
- Blocked state
- A task waiting for an event, such as a mutex or semaphore being given. It uses no processor time while it waits.
- Binary semaphore
- A FreeRTOS signal that holds 0 or 1. One task or ISR gives it, another task takes it; it need not be given back.
- ISR (interrupt service routine)
- A short function the CPU runs at once when hardware signals an event, such as a pin's falling edge, in the middle of whatever task is running.
- FromISR functions
- The FreeRTOS calls that are safe inside an ISR, such as xSemaphoreGiveFromISR(). They never block and report whether a higher-priority task was woken.
- Deferred interrupt processing
- Keeping the ISR tiny (note the event, give a semaphore) and doing the real work in a task the ISR wakes.
Notes and sources
- Target: an ESP32 DevKit (Arduino-ESP32 core). The ESP32 has two cores; both tasks are pinned to core 1 with xTaskCreatePinnedToCore() so only one runs at a time, which is the story told here. The mutex works the same across cores.
- Task A prints in two calls on purpose: the mix-up happens between calls. The FreeRTOS book shows the same fault on an LCD, where a pre-empted write gives "Hello wAbort, Retry, Fail?orld".
- A mutex uses priority inheritance, so the task that takes it must always give it back. The lesson "Priority inversion and priority inheritance" explains why that matters.
- Inside an ISR use only the API calls whose names end in FromISR. Mutexes must not be used from ISRs at all, and xSemaphoreGive() must not be called from one.
- A binary semaphore holds at most one give. If the button bounces or is pressed twice before B runs, the extra gives are lost, so B should handle everything pending each time it wakes. The lesson "Debouncing a button" covers the bounce.
- portMAX_DELAY waits forever only when INCLUDE_vTaskSuspend is 1 in FreeRTOSConfig.h, as it is on the ESP32. A real handler often passes a timeout instead, so it can notice a fault.
- FreeRTOS-Kernel: include/semphr.h (semaphore and mutex API reference)
- R. Barry, Mastering the FreeRTOS Real Time Kernel, ch. 4: Task Management (Blocked state, scheduling)
- R. Barry, Mastering the FreeRTOS Real Time Kernel, ch. 7: Interrupt Management (deferred processing, portYIELD_FROM_ISR)
- R. Barry, Mastering the FreeRTOS Real Time Kernel, ch. 8: Resource Management (mutexes, priority inheritance)
- Espressif ESP-IDF: FreeRTOS (IDF) API reference, xTaskCreatePinnedToCore()
- Espressif ESP-IDF: xtensa portmacro.h (portYIELD_FROM_ISR)
- Espressif ESP-IDF: FreeRTOSConfig.h (INCLUDE_vTaskSuspend)
- Arduino-ESP32 documentation: GPIO API (attachInterrupt, FALLING, INPUT_PULLUP)
Quiz Unlocks after the last step.