What is mutual exclusion and what is a critical section?
Mutual exclusion is the requirement that when one task is accessing a shared resource, no other task can access it simultaneously. It prevents race conditions where two tasks read-modify-write the same variable and produce corrupt results.
A critical section is the region of code that accesses the shared resource and must execute atomically with respect to other tasks. In an embedded RTOS, there are several ways to implement critical sections depending on the situation: (1) disabling interrupts — the simplest method, guarantees atomicity but blocks all interrupts and increases worst-case interrupt latency, so it should only be used for very short sections; (2) using a mutex — the preferred method for longer sections, because it only blocks tasks that need the same resource while allowing unrelated tasks and interrupts to proceed; (3) using a scheduler lock — suspends task switching but keeps interrupts enabled, useful when you need atomicity against other tasks but not against ISRs.
In embedded interviews, a common follow-up is: "When would you disable interrupts instead of using a mutex?" The answer is when the critical section is very short (a few instructions) and a mutex would add unnecessary overhead, or when the shared resource is accessed by both a task and an ISR (since ISRs cannot block on a mutex). For ISR-task shared data, the typical pattern is to disable interrupts briefly in the task, or use a lock-free data structure like a ring buffer.
Source: Operating Systems & RTOS Q&A
