</>EmbeddedInterview

What is a critical section and how do you implement one on bare metal?

MediumEmbedded C

Short answer: A critical section is a piece of code that must not be interrupted by anything that accesses the same shared data. On a single-core MCU the simplest implementation is to disable interrupts on entry and restore the previous state on exit; saving and restoring (instead of blindly re-enabling) makes it safe to nest.

#include "cmsis_compiler.h"

static inline uint32_t irq_save(void)
{
    uint32_t primask = __get_PRIMASK();   /* 1 if interrupts were already disabled */
    __disable_irq();                      /* CPSID i */
    return primask;
}

static inline void irq_restore(uint32_t primask)
{
    __set_PRIMASK(primask);               /* re-enable only if they were enabled before */
}

void counter_add(uint32_t n)
{
    uint32_t s = irq_save();
    shared_counter += n;                  /* read-modify-write is now safe from ISRs */
    irq_restore(s);
}

Why save/restore: if a function with a critical section is called from inside another critical section, a plain __enable_irq() at its end would enable interrupts too early, in the middle of the outer section.

Masking only some interrupts (Cortex-M3 and later):

uint32_t old = __get_BASEPRI();
__set_BASEPRI_MAX(5u << (8u - __NVIC_PRIO_BITS));   /* block priority 5 and lower urgency */
/* ... */
__set_BASEPRI(old);

Interrupts more urgent than the threshold still run, so their latency is unaffected. FreeRTOS uses this for taskENTER_CRITICAL() on Cortex-M3+.

Other ways to protect shared data

  • Disable only the one peripheral's interrupt (NVIC_DisableIRQ(USART2_IRQn)) when only that ISR shares the data.
  • Atomic instructions: LDREX/STREX (C11 atomics) on Cortex-M3+; not available on M0/M0+.
  • Lock-free design: single-producer/single-consumer ring buffers where each index is written by only one side.
  • RTOS: taskENTER_CRITICAL() from tasks, taskENTER_CRITICAL_FROM_ISR() in ISRs, or a mutex if the section is long and no ISR is involved.

Rules

  • Keep it as short as possible: everything inside adds interrupt latency.
  • Never call blocking functions inside it.
  • On multi-core systems disabling interrupts on one core does not stop the other core: you need a spinlock or hardware semaphore (e.g. the HSEM on STM32H7 dual-core) as well.