Sharing with a mutex
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.
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.
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=.
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.
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.
Waking a task from an ISR
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.
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.
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.
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.
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.
What happens
;; step 1/10 · shared
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
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. 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.