Synchronization vs communication
Once firmware is split into several tasks, they need to cooperate. Two related needs come up:
- Synchronization is about timing and ordering: making one task wait until another has done something, or making sure two tasks don’t use the same resource at the same time. In plain terms, synchronization means coordinating events so they happen in a safe order.
- Communication is about moving data: getting a sensor reading, a command, or a buffer of bytes from one task, or an interrupt, to another.
RTOSes provide a set of primitives for both: mutexes, semaphores, queues, event flags, and more. The examples below use the FreeRTOS API because it’s widely used. The same ideas exist in every RTOS under slightly different names, and there’s a mapping table near the end.
Why tasks need coordination: a race condition
Consider two tasks that count received packets in a shared variable:
static volatile uint32_t packet_count = 0;
void vRadioTask(void *pv) { for (;;) { wait_for_radio_packet(); packet_count++; } }
void vSerialTask(void *pv) { for (;;) { wait_for_serial_packet(); packet_count++; } }
packet_count++ looks like one operation, but on most processors it’s three: load the value into a register, add one, and store it back. If the scheduler switches from the radio task to the serial task between the load and the store, both tasks read the same old value, and one increment is lost.
volatile doesn’t help. It stops the compiler from caching the variable, but it doesn’t make the read-modify-write atomic. This kind of bug may show up once a week in the field and never on the bench, which is why it’s worth understanding the tools that prevent it.
Critical sections: the bluntest tool
The simplest protection is to stop anything else from running while you touch the shared data:
taskENTER_CRITICAL();
packet_count++;
taskEXIT_CRITICAL();
In FreeRTOS on many ports, a critical section masks interrupts up to a configured priority, which also prevents context switches. It’s fast and effective for a few instructions. But every microsecond inside a critical section is a microsecond of added latency for interrupts and higher-priority tasks, so critical sections should be very short: a few reads and writes, never a loop or a driver call.
A related option is suspending the scheduler (vTaskSuspendAll() / xTaskResumeAll()), which stops task switches but leaves interrupts running. It’s useful for slightly longer operations that don’t involve ISRs, but it still delays every other task.
For a single variable, also consider whether you need sharing at all. Often each task can keep its own counter and a third task can sum them. On cores and compilers that support it, C11 atomics (<stdatomic.h>) can provide atomic increments without a critical section.
Mutexes: protecting shared resources
A mutex (mutual exclusion lock) guards a resource that only one task should use at a time: an I2C bus, a shared configuration structure, a display, a file system. A task takes the mutex before using the resource and gives it back when finished. If another task already holds it, the caller blocks until it’s released or a timeout expires.
static SemaphoreHandle_t xI2cMutex;
void app_init(void)
{
xI2cMutex = xSemaphoreCreateMutex();
configASSERT(xI2cMutex != NULL);
}
bool sensor_read(uint8_t reg, uint8_t *out)
{
if (xSemaphoreTake(xI2cMutex, pdMS_TO_TICKS(10)) != pdTRUE) {
return false; /* bus busy for too long: report it */
}
bool ok = i2c_read_register(SENSOR_ADDR, reg, out);
xSemaphoreGive(xI2cMutex);
return ok;
}
Key properties of a mutex:
- It has an owner. The task that took it is expected to give it back. Giving a mutex from another task is a design error.
- In FreeRTOS, Zephyr, ThreadX, and most RTOSes, mutexes support priority inheritance (in ThreadX it’s an option when creating the mutex), explained below.
- Mutexes shouldn’t be used from ISRs. An interrupt can’t block, and it can’t sensibly “own” anything.
- Keep the locked region as short as possible. Don’t hold a mutex while waiting on something slow and unrelated.
Semaphores: signaling events
A semaphore is a counter used for signaling. Giving it increments the count (or sets it, for a binary semaphore). Taking it decrements the count, blocking if it’s already zero.
Binary semaphores
A binary semaphore is either available or not. It’s commonly used to say “something happened”: an ISR gives the semaphore when a DMA transfer completes, and a task blocked on xSemaphoreTake() wakes up to process the data. The giver and taker are different parties, and there’s no ownership.
Counting semaphores
A counting semaphore can count above one. Two common uses:
- Counting events so none are lost when several arrive before the task runs.
- Managing a pool of identical resources, such as four DMA buffers. The count starts at four, each user takes one, and returns it when done.
Mutex vs semaphore
This is one of the most common points of confusion in RTOS programming. A short rule:
- Use a mutex to protect a resource. The same task locks and unlocks it, and you want priority inheritance.
- Use a semaphore to signal that something happened, or to count available items. One party gives it, and another takes it.
In FreeRTOS, mutexes are created through the semaphore API (xSemaphoreCreateMutex()), which adds to the confusion, but they behave differently. Using a binary semaphore as a lock works until a priority inversion happens, and then it doesn’t.
Priority inversion and priority inheritance
Priority inversion happens when a high-priority task waits for a resource held by a low-priority task, and a medium-priority task that doesn’t need the resource keeps preempting the low-priority one. The high-priority task ends up waiting for the medium-priority task, possibly for an unbounded time.
- Low-priority task L takes the mutex.
- High-priority task H becomes ready, preempts L, tries to take the mutex, and blocks.
- Medium-priority task M becomes ready. It’s higher than L, so it runs, and keeps running.
- L can’t run to release the mutex, so H waits as long as M keeps the CPU.
The well-known example is NASA’s Mars Pathfinder lander in 1997. After landing it experienced repeated system resets. Engineers traced them to priority inversion: a low-priority task held a mutex protecting a shared data bus, a high-priority bus-management task was blocked waiting for it, and medium-priority tasks kept running. A timer detected that the bus task hadn’t completed and reset the system. The fix was to enable priority inheritance on that mutex, which was done by uploading a change to the spacecraft.
Priority inheritance solves the basic problem by temporarily raising L’s priority to H’s while L holds the mutex. M can no longer preempt L, so L finishes quickly and releases the lock. Some RTOSes also offer the priority ceiling protocol, where a mutex is given a fixed ceiling priority that the holder is raised to whenever it locks the mutex.
Inheritance bounds the inversion but doesn’t eliminate it. H still waits for L’s critical section, so keeping locked regions short still matters. For how blocking time fits into schedulability analysis, see real-time scheduling and multitasking in embedded systems.
Deadlock and how to avoid it
A deadlock occurs when tasks wait on each other in a cycle. For example, task A holds mutex 1 and waits for mutex 2, while task B holds mutex 2 and waits for mutex 1. Neither can proceed.
Practical defenses:
- Lock ordering: if code ever needs more than one mutex, always take them in the same global order.
- Avoid nested locks where you can. Restructure so each operation needs only one.
- Use timeouts rather than waiting forever in production code, and treat a timeout as an error worth logging.
- Don’t call unknown code (callbacks, logging functions that might take their own locks) while holding a mutex.
Passing data between tasks
Message queues
A queue is a fixed-size FIFO of fixed-size items. In FreeRTOS, items are copied into and out of the queue, so the sender can reuse its variable immediately. Queues combine communication and synchronization: a task blocked on an empty queue wakes up when data arrives.
typedef struct {
uint32_t timestamp_ms;
int16_t temp_c_x10; /* tenths of a degree */
} reading_t;
static QueueHandle_t xReadingQueue;
void vSensorTask(void *pv)
{
for (;;) {
reading_t r = { .timestamp_ms = now_ms(), .temp_c_x10 = read_temp() };
if (xQueueSend(xReadingQueue, &r, pdMS_TO_TICKS(5)) != pdTRUE) {
dropped_readings++; /* queue full: consumer is falling behind */
}
vTaskDelay(pdMS_TO_TICKS(100));
}
}
void vLoggerTask(void *pv)
{
reading_t r;
for (;;) {
if (xQueueReceive(xReadingQueue, &r, portMAX_DELAY) == pdTRUE) {
log_reading(&r);
}
}
}
/* during init: */
/* xReadingQueue = xQueueCreate(8, sizeof(reading_t)); */
Size queues for bursts, and decide explicitly what happens when one is full. Blocking the sender, dropping the new item, and overwriting the oldest are all valid in different situations. For large data, queue a pointer or buffer index rather than copying kilobytes, but then you need a clear rule about who owns the buffer.
Stream and message buffers
FreeRTOS also provides stream buffers (a byte stream, good for UART data) and message buffers (variable-length messages). They’re lighter than queues but designed for a single writer and a single reader. Other RTOSes have similar pipes and FIFOs.
Shared data plus a mutex
Sometimes the right model is shared state, such as “the latest configuration” or “the current setpoint”, rather than a stream of messages. Protect it with a mutex, keep the locked region to a quick copy, and work on the copy afterward.
Lock-free ring buffers
A ring buffer with exactly one producer and one consumer can be made safe without locks, as long as each index is written by only one side and reads and writes of the index are atomic on your processor. This is a common pattern between an ISR and a task for high-rate data. Get it reviewed carefully: memory ordering, index wrap-around, and the full/empty distinction are classic sources of subtle bugs.
Event flags and task notifications
- Event groups / event flags let a task wait for one or more bits to be set, such as “wait until Wi-Fi is connected and the time is synchronized.” They’re good for state conditions that several tasks care about.
- Direct-to-task notifications (FreeRTOS) give each task a built-in notification value that other tasks or ISRs can set, increment, or overwrite. They can stand in for a binary or counting semaphore, or a simple event flag, when there’s exactly one receiving task. FreeRTOS documents them as faster and lighter on RAM than the equivalent semaphore. They can’t have multiple waiters, and the receiving task must be known in advance.
Working with interrupts
Interrupt service routines have special rules:
- An ISR must never block. It can’t wait on a mutex, a full queue, or a semaphore.
- In FreeRTOS, use the
FromISRvariants of API calls inside ISRs, such asxQueueSendFromISR(),xSemaphoreGiveFromISR(), andvTaskNotifyGiveFromISR(). Calling the normal versions from an ISR is a common cause of crashes. - On Cortex-M ports, ISRs that call FreeRTOS APIs must have a priority that is numerically at or above (logically at or below)
configMAX_SYSCALL_INTERRUPT_PRIORITY. Getting this wrong typically trips an assertion ifconfigASSERT()is defined, or causes intermittent corruption if it isn’t.
The standard pattern is deferred interrupt processing: keep the ISR tiny, and hand the real work to a task.
static TaskHandle_t xAdcTaskHandle;
void ADC_IRQHandler(void)
{
BaseType_t xWoken = pdFALSE;
adc_clear_interrupt_flag();
vTaskNotifyGiveFromISR(xAdcTaskHandle, &xWoken);
portYIELD_FROM_ISR(xWoken); /* switch now if the woken task has higher priority */
}
void vAdcTask(void *pv)
{
for (;;) {
ulTaskNotifyTake(pdTRUE, portMAX_DELAY); /* sleep until the ISR signals */
process_adc_samples();
}
}
portYIELD_FROM_ISR() makes the woken task run as soon as the ISR exits, instead of at the next tick, which is what gives this pattern its low latency.
Choosing the right primitive
| You need to… | Use |
|---|---|
| Protect a shared resource (bus, struct, peripheral) | Mutex, with priority inheritance |
| Protect a few instructions on shared data | Short critical section, or an atomic operation |
| Signal “this happened” from an ISR to one task | Task notification or binary semaphore |
| Count events or manage a pool of N items | Counting semaphore |
| Send data items from one or more producers | Message queue |
| Stream bytes from one producer to one consumer | Stream buffer, or a lock-free ring buffer |
| Wait until several conditions are all true | Event group / event flags |
| Share “latest value” state | Mutex-protected struct, or a length-1 queue with overwrite |
Same ideas, different names
| Concept | FreeRTOS | Zephyr | ThreadX |
|---|---|---|---|
| Mutex | xSemaphoreCreateMutex() |
k_mutex |
tx_mutex |
| Semaphore | xSemaphoreCreateBinary() / ...Counting() |
k_sem |
tx_semaphore (counting) |
| Message queue | xQueueCreate() |
k_msgq |
tx_queue |
| Event flags | Event groups | k_event |
tx_event_flags |
| Byte stream | Stream buffer | k_pipe |
– (often a queue or custom ring buffer) |
The semantics differ in the details, such as how timeouts are expressed, whether messages are copied, and how priority inheritance is configured, so check your RTOS’s documentation. If you’re choosing between these three, see FreeRTOS vs Zephyr vs ThreadX.
Common mistakes
- Using a binary semaphore as a lock, then hitting priority inversion.
- Calling blocking or non-
FromISRAPI functions from an interrupt. - Holding a mutex while calling
printf(), writing flash, or waiting on another queue. - Waiting forever (
portMAX_DELAY) in places where a stuck peer should be detected and handled. - Sharing a variable “just this once” without protection because “it’s only a flag.” That’s sometimes fine for a single aligned word written by one side, but think it through rather than assuming.
- Undersized queues that fill during bursts, with no handling for the full case.
- Large queue items or deep call chains inside callbacks that quietly push a task’s stack over its limit. See how to size RTOS task stacks and detect stack overflow.
Frequently asked questions
What is the definition of synchronization in embedded systems?
Synchronization is the coordination of tasks and interrupts so that events happen in a safe order. That includes making a task wait for an event, and making sure only one task uses a shared resource at a time.
When should I use a queue instead of a mutex-protected variable?
Use a queue when each item matters and should be processed in order, like commands or samples. Use a protected variable when only the latest value matters, like a current setpoint, and older values can be overwritten.
Do I need synchronization in a bare-metal super loop?
Yes, between the main loop and interrupts. A super loop has no task preemption, but an ISR can still interrupt the loop in the middle of a read-modify-write. Short critical sections and careful flag handling are the usual tools. See RTOS vs super loop for how the two architectures compare.