Try Embedded

RTOS synchronisation primitives

Mutexes, semaphores, queues, event flags and priority inversion.

Why tasks need synchronisation

With preemption, any task can be interrupted between any two instructions. If two tasks touch the same data or the same peripheral, they will eventually interleave in a way that corrupts it, rarely and unreproducibly. Synchronisation primitives make those interactions safe and let tasks wait for each other without spinning.

The race, demonstrated

counter++ compiles to load, add, store. If a task is preempted between the load and the store and another task increments the same counter, one increment is lost:

#include <stdio.h>

static int counter;

int main(void) {
  /* Task A and task B each do counter++ once, interleaved by a preemption. */
  int a_reg = counter;     /* A: load 0 */
                           /* -- preempted: B runs to completion -- */
  int b_reg = counter;     /* B: load 0 */
  b_reg = b_reg + 1;
  counter = b_reg;         /* B: store 1 */
                           /* -- A resumes with its stale copy -- */
  a_reg = a_reg + 1;
  counter = a_reg;         /* A: store 1 */

  printf("two increments, counter = %d\n", counter);
  return 0;
}

The region between reading shared state and writing it back is a critical section. Only one task may be inside it at a time.

The primitives

PrimitivePurposeHas an ownerPriority inheritanceUsable from an ISR
Critical section (interrupts or scheduler off)Very short sections; protect against ISRs——Yes (save/restore mask)
MutexMutual exclusion around a shared resourceYes: only the taker may give itYesNo
Binary semaphoreSignal that an event happenedNoNoGive: yes
Counting semaphoreCount events, or manage N identical resourcesNoNoGive: yes
QueuePass data (copies) between tasks or from ISRs——Send: yes
Event group / flagsWait for any or all of several conditions——Set: yes
Task notification (FreeRTOS)Fast, lightweight signal or value to one task——Yes

Mutex versus semaphore

This is the most-asked RTOS interview question, and the answer is about ownership and intent:

  • A mutex is a lock. The task that takes it must give it back. It protects a resource (the I2C bus, a shared struct). Because it has an owner, the kernel can apply priority inheritance, and can detect errors such as a task releasing a mutex it does not hold. A recursive mutex can be taken again by its owner.
  • A semaphore is a signal. One party gives, a different party takes: an ISR gives "data ready", a task takes it and processes. There is no owner, so no priority inheritance.

Using a binary semaphore as a lock works until priority inversion happens, which is why it is a bug.

Priority inversion

Three tasks: High (H), Medium (M), Low (L). L takes a mutex protecting the SPI bus. H becomes ready and wants the bus, so it blocks waiting for L. Now M becomes ready. M has higher priority than L, so M runs, and keeps running, while L (holding the bus) never gets the CPU. H, the most urgent task, is effectively blocked by M, an unrelated medium task, for an unbounded time.

This took down the Mars Pathfinder lander's software in 1997 with repeated resets until engineers enabled priority inheritance on the offending mutex remotely.

Priority inheritance: while H waits for a mutex held by L, L temporarily runs at H's priority, so M cannot preempt it. L finishes its critical section quickly, releases the mutex, drops back to its own priority, and H runs. The blocking time is now bounded by L's critical section.

Priority ceiling: each mutex has a ceiling equal to the highest priority of any task that uses it; a task holding it runs at the ceiling. This prevents inversion and also certain deadlocks, at the cost of some unnecessary blocking.

Deadlock

Task 1 holds mutex A and waits for B; task 2 holds B and waits for A. Neither can proceed. Prevention:

  • Lock ordering: always take multiple mutexes in the same global order.
  • Hold as few locks as possible, for as short as possible; never call unknown code (callbacks) while holding one.
  • Use timeouts on takes in debug builds and log when they expire.

Queues: the default way to share data

Instead of sharing a variable under a lock, give each resource one owner task and send it messages. A queue copies the data, so sender and receiver never share memory, and the receiver blocks efficiently until something arrives.

typedef struct { uint8_t channel; int32_t value; } reading_t;
QueueHandle_t readings = xQueueCreate(16, sizeof(reading_t));

/* producer */
reading_t r = { 2, adc_read(2) };
if (xQueueSend(readings, &r, pdMS_TO_TICKS(10)) != pdPASS) dropped++;

/* consumer */
reading_t r;
while (xQueueReceive(readings, &r, portMAX_DELAY) == pdPASS) log_reading(&r);

Size queues for the worst-case burst, and decide what happens when one is full (drop, overwrite the oldest, block the producer).

Event groups

When a task must wait for a combination of conditions (Wi-Fi connected and time synchronised and configuration loaded), an event group lets it wait for all bits, or any bit, in a single call, instead of chaining semaphores.

Choosing

  • Protecting a shared resource used by several tasks: mutex.
  • An ISR telling a task "something happened": task notification or binary semaphore.
  • Passing data: queue (or a stream/message buffer for byte streams).
  • Waiting for several conditions: event group.
  • A few instructions touching data shared with an ISR: critical section.

Pitfall: Taking a mutex inside an ISR is never allowed: an ISR cannot block, and it is not a task, so it cannot own a mutex or inherit priority. ISRs give semaphores, send to queues or notify tasks, always with the FromISR API.

Interview question: Explain priority inversion and how to prevent it.

Answer: A high-priority task blocks on a resource held by a low-priority task, and a medium-priority task that does not need the resource preempts the low one, so the high task waits for an unbounded time behind unrelated work. Prevent it with mutexes that implement priority inheritance (the holder temporarily runs at the waiter's priority) or a priority ceiling protocol, keep critical sections short, and avoid sharing resources between tasks of very different priorities where possible, for example by giving the resource to a single owner task fed by a queue.

Interview question: What is the difference between a mutex and a semaphore?

Answer: A mutex is a locking mechanism with ownership: the task that takes it must release it, it protects a shared resource, supports priority inheritance and sometimes recursion, and cannot be used from an ISR. A semaphore is a signalling mechanism without ownership: one context gives and another takes, it is used to signal events (including from ISRs) or, as a counting semaphore, to count available resources or pending events. Using a semaphore for mutual exclusion loses priority inheritance and ownership checks.

Build it: stop priority inversion from starving the motor

This is step 3 of the module project. The motor task (high priority) and the logger task (low priority) share the SPI flash, guarded by a mutex. Now Bluetooth (medium priority) runs often too. The bug that froze a Mars lander can happen here: the logger holds the mutex, the motor task waits for it, and Bluetooth keeps the logger from ever running to release it. The motor misses a dose. The fix is priority inheritance.

Lab: A mutex with priority inheritance

A miniature kernel is provided: three tasks with base priorities (motor 3, bluetooth 2, logger 1), each ready or blocked, and running(), which returns the ready task with the highest effective priority. You write the mutex.

  • mutex_lock(t): if the mutex is free, task t owns it and the call returns true. Otherwise t blocks (becomes not ready), joins the waiters, and the call returns false. If t's effective priority is higher than the owner's, the owner inherits it: its effective priority is raised to t's.
  • mutex_unlock(t): only the owner may unlock (otherwise return false). The owner's effective priority goes back to its base priority. If tasks are waiting, the highest-priority waiter becomes the new owner and is made ready again. Return true.

The checks replay the timeline that causes the inversion and print who runs at each step.

Going deeper

Interview question: How would you share data between a payment terminal's card reader, display and network tasks safely?

Answer: Give each piece of data an owner and pass messages through queues rather than sharing variables. Where sharing is unavoidable, use a mutex with priority inheritance, keep critical sections short, never block while holding one, and take multiple locks in a fixed order to avoid deadlock.

Interview question: What is a recursive mutex and when is it needed?

Answer: A mutex that the same task can take several times without deadlocking itself, keeping a count and releasing only when given back the same number of times. It is needed when a function holding a lock calls another function that takes the same lock, such as layered driver code. It can hide poor lock design, so prefer restructuring code so locks are taken once at a clear level.

Interview question: How do event groups differ from semaphores?

Answer: An event group holds a set of flag bits that several tasks or interrupts can set, and a task can wait for any or all of a chosen combination of bits, optionally clearing them on exit, and several tasks can wait on the same bits. A semaphore represents a single count or signal consumed by one taker. Event groups suit waiting for several conditions, such as network up and time synchronised; semaphores suit signalling single events.

Explain it: In your own words, explain why a deadlock happens with two mutexes and how lock ordering prevents it.

Answer: A deadlock happens when task 1 holds mutex A and waits for mutex B, while task 2 holds B and waits for A: each waits for something the other will never release, so both stop forever. If every task that needs both mutexes always takes them in the same global order, A before B, then a task holding B can never be waiting for A, so the circular wait cannot form. Holding locks briefly and never calling unknown code while holding one also reduces the risk.