</>EmbeddedInterview

How do you protect a shared resource between a task and an ISR?

MediumRTOS & Real-Time Systems

Short answer: A mutex cannot be used, because an ISR cannot block or own a mutex. Instead: protect the task's short access with a critical section that masks the interrupt (taskENTER_CRITICAL() / taskEXIT_CRITICAL(), which raises BASEPRI on Cortex-M3+); design the data flow so each variable has a single writer (lock-free ring buffer); or pass data through an RTOS queue/stream buffer and let only the task own the resource.

Options

  1. Critical section in the task
/* task side */
taskENTER_CRITICAL();
uint32_t count = shared_count;    /* read-modify-write that the ISR also does */
shared_count = 0;
taskEXIT_CRITICAL();

/* ISR side: if a higher-priority ISR can also touch it */
UBaseType_t s = taskENTER_CRITICAL_FROM_ISR();
shared_count++;
taskEXIT_CRITICAL_FROM_ISR(s);

Keep it a few instructions long; it delays all interrupts at or below the masked priority.

  1. Disable only that interrupt (NVIC_DisableIRQ / NVIC_EnableIRQ) around the access, when only one ISR is involved and you do not want to affect other interrupts.

  2. Lock-free single-producer/single-consumer structures: the ISR writes the head, the task writes the tail; no locks needed on a single core (add barriers on Cortex-M7/multi-core).

  3. Message passing: the ISR sends the event/data to a queue, stream buffer or task notification; the task is the only one that touches the resource. This is usually the cleanest design.

  4. Atomic operations for single variables (C11 atomics on Cortex-M3+).

Do not: take a mutex in an ISR, call blocking APIs from it, or rely on volatile alone for read-modify-write operations.

Interrupt priority check: if the ISR calls ...FromISR APIs, its priority must be at or below configMAX_SYSCALL_INTERRUPT_PRIORITY (numerically ≥).