ENع
←Mutexes and ISR semaphores
Lesson 41 · Bare metal versus an RTOS

FreeRTOS mutexes and waking a task from an ISR

14 min10 steps5 questionsAdvanced
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”.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 41 · Interactive
01 / 10

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
  > 21
Loading figure…
or ← →
Read the lesson step by step
  1. 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
      > 21
  2. A 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 it
  3. Task 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=
  4. 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 takes
  5. A 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
      > pressed
  6. B 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 waits
  7. The 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 ISRs
  8. The 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 = pdTRUE
  9. Switch 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 back
  10. Short 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)

Quiz Unlocks after the last step.