</>EmbeddedInterview

What is a deadlock and how do you prevent it?

MediumRTOS & Real-Time Systems

Short answer: A deadlock occurs when two or more tasks each wait for a resource held by another, so none can proceed. It needs all four Coffman conditions: mutual exclusion, hold-and-wait, no pre-emption of resources, and circular wait. Prevent it by breaking at least one condition, most practically by always taking locks in the same global order.

Classic example

/* Task A */                     /* Task B */
take(mutex_spi);                 take(mutex_flash);
take(mutex_flash);   /* waits */ take(mutex_spi);    /* waits: deadlock */

Prevention strategies

Strategy Breaks Practice
Global lock ordering circular wait document an order (e.g. always SPI before flash); lockdep in Linux checks it at run time
Take all locks at once, or none hold and wait try each lock; on failure release everything and retry later
Timeouts on take indefinite waiting detect and recover (log, release, retry); not a full fix
Single owner / message passing mutual exclusion on shared state one task owns the SPI bus; others send requests via a queue
Priority ceiling protocol circular wait (uniprocessor) in OSEK/AUTOSAR systems
Avoid nested locks most cases keep critical sections small and flat

Detection: watchdogs (tasks stop checking in), tracing tools showing tasks blocked forever on mutexes, FreeRTOS/Zephyr thread analyzers, and in the debugger, the RTOS-aware view listing each task's blocking object and each mutex's owner.

Related problems: the dining philosophers (five philosophers, five forks, each needs two) is the textbook deadlock: fix it by ordering resources (always pick the lower-numbered fork first) or limiting how many can try at once.

Self-deadlock: a task taking a non-recursive mutex it already holds, or an ISR waiting on something a task must release. Recursive mutexes fix the first (but often hide a design problem).