In embedded software on NXP MCUs such as the S32K or i.MX RT family, a critical section protects shared state from being modified concurrently by interrupt handlers.
Explain how to prevent an interrupt from disrupting a critical section of code. Your answer should address:
Focus on low-level programming behavior rather than RTOS theory. The interviewer expects a practical systems explanation, including common MCU patterns such as saving the current interrupt state, disabling interrupts, executing the protected code, and restoring the original state afterward.
A critical section is a block of code that accesses shared state and must execute atomically relative to competing execution contexts. In embedded systems, the competing context is often an interrupt service routine that can preempt the main code at almost any instruction boundary.
shared_counter += 1 # Unsafe if an ISR can also modify it
Interrupt masking temporarily prevents some or all interrupts from being serviced while protected code runs. On ARM Cortex-M devices commonly used by NXP, this is often done with instructions or intrinsics that set PRIMASK or BASEPRI.
state = __get_PRIMASK()
__disable_irq()
# critical section
__set_PRIMASK(state)
Good code saves the previous interrupt state before disabling interrupts, then restores exactly that state afterward. This avoids accidentally enabling interrupts that were already disabled by an outer caller or another protection layer.
old_state = __get_PRIMASK()
__disable_irq()
# protected work
__set_PRIMASK(old_state)
Disabling interrupts improves atomicity but increases interrupt latency. If the critical section is too long, time-sensitive peripherals, watchdog servicing, or real-time deadlines may be missed.
Not every shared update requires globally disabling interrupts. For small operations such as incrementing flags or swapping pointers, hardware atomic instructions, lock-free patterns, or narrower interrupt priority masking may be safer and faster.
volatile uint32_t flag;
flag = 1; // May be enough if write is naturally atomic