Explain the difference between a mutex and a semaphore in an RTOS, with examples.
What the interviewer wants to hear
- Mutex protects a shared resource; has an owner and must be released by the same task
- Mutex supports priority inheritance
- Binary semaphore is used for signalling, for example from ISR to task
- Counting semaphore tracks multiple resources or events
- Do not take mutexes in ISRs
Model answer
A mutex is for mutual exclusion around a shared resource, like an SPI bus or a UART used by several tasks. It has an owner: the task that takes it must give it back. In FreeRTOS, mutexes support priority inheritance, which prevents priority inversion when a low-priority task holds the lock. A semaphore is mainly for signalling and counting. A binary semaphore is like a flag: an ISR gives it when data is ready, and a task blocked on it wakes up and processes the data. In FreeRTOS, direct task notifications are a faster option for this. A counting semaphore tracks several identical resources, for example five free buffers, or counts events that arrive faster than they are processed. Mutexes should not be used from ISRs, because an ISR cannot block or own a lock. Using a semaphore where a mutex is needed loses priority inheritance and ownership checks.
Can you answer it under time pressure?
Take a timed medium round and get scored on every answer.
More medium Embedded Systems Engineer questions
- How would you write a driver for a new I2C temperature sensor?
- A device freezes randomly once every few days in the field. How do you debug it?
- Explain the memory layout of a typical microcontroller program: .text, .data, .bss, stack and heap.
- When would you use fixed-point arithmetic instead of floating point on a microcontroller?
- What is DMA, when would you use it, and what pitfalls do you watch for?
- Design firmware that receives text commands over UART, like "SET LED 1", and responds reliably.
- Explain how the CAN bus works and why it is popular in automotive and industrial systems.
- Your firmware is close to the flash and RAM limits of the MCU. How do you reduce memory usage?
- How would you design a watchdog strategy for firmware running several RTOS tasks?