Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท RTOS and Scheduling

RTOS Synchronization: Queues, Semaphores and Mutexes

Learn the RTOS tools for task communication: queues, binary and counting semaphores, mutexes and event flags, plus priority inversion, priority inheritance and deadlock.

Once a system has several tasks, they must communicate and share resources. A sensor task produces readings that a display task shows; two tasks need the same SPI bus; an ISR must wake a task when data arrives. Doing this with plain global variables brings back every problem from the shared data lesson, now with a preemptive scheduler that can switch tasks between any two instructions.

An RTOS provides safe tools for the job. This lesson explains each one, when to use it, and the two classic problems that come with them: priority inversion and deadlock.

The toolbox

Tool What it does Typical use
Queue Thread-safe FIFO that copies items in and out Passing messages and sensor readings between tasks, or from an ISR to a task
Binary semaphore A flag that is either available or not; a task blocks until it is given Signaling: "ISR tells task that an event happened"
Counting semaphore A counter with give and take Counting events, or managing a pool of N identical resources
Mutex A lock with an owner; only the task that took it should release it Protecting a shared resource (bus, buffer, device)
Event group / flags A set of bits a task can wait on, in any combination Waiting for "A and B" or "A or B"
Direct task notification A light-weight signal or value sent straight to one task Fast ISR-to-task wake-up with minimum RAM

Queues

A queue is the most useful tool because it moves data and synchronizes. The receiver blocks (costing no CPU) until an item arrives or a timeout expires. The sender can block if the queue is full. Because items are copied, producer and consumer need not share memory, so nothing needs a lock. Pass small structs by value; pass larger items as pointers to buffers whose ownership moves with the message.

C
// Read-only: FreeRTOS queue between a sensor task and a logger task
typedef struct { uint32_t timestamp; int16_t temperature; } reading_t;
static QueueHandle_t readings;

void vSensorTask(void *p) {
    for (;;) {
        reading_t r = { xTaskGetTickCount(), read_temperature() };
        xQueueSend(readings, &r, 0);               // do not wait if full
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

void vLoggerTask(void *p) {
    reading_t r;
    for (;;) {
        if (xQueueReceive(readings, &r, portMAX_DELAY) == pdTRUE) {   // sleep until data
            log_reading(&r);
        }
    }
}
// in main: readings = xQueueCreate(8, sizeof(reading_t));

Semaphores

A binary semaphore is the standard link between an interrupt and a task. The ISR "gives" it, and the task, which has been blocked waiting to "take" it, becomes ready and runs soon after the ISR ends. The ISR stays tiny; the real work happens in task context where you may call blocking functions. In FreeRTOS the ISR uses the FromISR variants and may request a context switch on exit.

A counting semaphore remembers how many times it has been given, which fixes the "lost events" problem from the interrupts lesson. It also models pools: start it at 3 for three identical DMA channels, take one before use, give it back after.

Mutexes

A mutex (mutual exclusion) guards a critical section. A task takes it before touching the shared resource and gives it back after. If another task already holds it, the caller blocks until it is released. Unlike a binary semaphore, a mutex has an owner: only the task that took it should give it, and good RTOS mutexes can apply priority inheritance (see below). Use semaphores for signaling and mutexes for protection; mixing the two up is a common bug.

Rules for mutex code:

  • Hold the lock for as short a time as possible. Never call a blocking function (like a long delay) while holding it.
  • Never take a mutex from an ISR. Interrupts cannot block.
  • Do not take it twice in the same task unless it is a recursive mutex.

Priority inversion

Suppose a low-priority task L holds a mutex, and a high-priority task H needs it. H must wait for L, which is expected. But now a medium-priority task M, which does not need the mutex, becomes ready. M has higher priority than L, so it preempts L, and L cannot finish and release the lock. H, the most important task, is now effectively waiting for M. The priorities have been inverted. If M runs for a long time, H misses its deadline. This bug has hit real spacecraft: it caused repeated system resets on the Mars Pathfinder lander in 1997 until it was patched remotely by enabling priority inheritance.

Priority inheritance is the fix: while H is blocked on a mutex held by L, the kernel temporarily raises L to H's priority. Then M can no longer preempt L, L finishes its critical section and releases the mutex, drops back to its own priority, and H runs.

The simulation below plays exactly this scenario twice, once without and once with inheritance. Task L (priority 1) arrives first and takes the lock for four ticks of work. H (priority 3) arrives at tick 1 and needs the lock. M (priority 2) arrives at tick 2 and needs 5 ticks of CPU, with no lock.

C Priority inversion with and without inheritance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Without inheritance, M runs for five ticks in the middle while H is stuck behind L; H finishes at tick 11. With inheritance, L is boosted, completes its critical section at once, and H finishes at tick 6. Most real-time kernels (FreeRTOS mutexes, Zephyr, ThreadX) implement inheritance on mutexes but not on plain semaphores, which is one more reason to use the right tool for the job.

Deadlock

Deadlock means two or more tasks wait for each other forever. The usual recipe is two locks taken in opposite orders: task A takes X then wants Y, while task B takes Y then wants X. Each holds what the other needs.

C A deadlock, and the lock-ordering fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Ways to avoid deadlock:

  1. Lock ordering. Define a global order for all locks and always take them in that order, as in the second run.
  2. Take fewer locks. If one lock is enough, use one. Better still, give each resource a single owner task and send it requests through a queue.
  3. Use timeouts. Taking a mutex with a timeout lets a task detect trouble and back off or reset.
  4. Do not call unknown code while holding a lock. A callback might try to take another lock.

Two related problems: starvation (a task never gets the CPU because higher-priority tasks keep running) and livelock (tasks keep reacting to each other without making progress). Both are design errors, not RTOS bugs: keep high-priority tasks short and mostly blocked.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which tool is best for passing sensor readings from one task to another, with the receiver sleeping until data arrives?

    A queue moves the data and blocks the receiver without using CPU until an item arrives.
  2. 2. What is priority inversion?

    The high-priority task is effectively delayed by the medium-priority task, though it never shares a resource with it.
  3. 3. How does priority inheritance fix priority inversion?

    With the holder boosted, the medium task cannot preempt it, so the lock is released quickly.
  4. 4. Two tasks take mutexes X and Y in opposite orders. What can happen?

    Each task may hold the lock the other one wants, so both wait forever.
  5. 5. Why should an ISR use a semaphore or queue FromISR function instead of a mutex?

    Interrupts run outside any task and must never block, so they signal with non-blocking calls.

Summary

  • Queues pass data safely and wake the receiver; semaphores signal events or count resources; mutexes protect shared resources and have an owner.
  • Priority inversion happens when a low task holding a lock is preempted by a medium task while a high task waits; priority inheritance fixes it.
  • Deadlock follows from locks taken in opposite orders; use a global lock order, fewer locks or timeouts.
  • Keep critical sections short, never block while holding a lock, and never take a mutex in an ISR.

Next: Scheduling Algorithms and Deadlines