C++ for Embedded · Interview question

Write an RAII guard for a critical section. Why is it better than paired enable/disable calls?

A strong answer

The guard saves and disables interrupts in its constructor and restores them in its destructor:

class CriticalSection {
    uint32_t primask_;
public:
    CriticalSection()  { primask_ = __get_PRIMASK(); __disable_irq(); }
    ~CriticalSection() { __set_PRIMASK(primask_); }
};

You use it as { CriticalSection cs; shared++; }. It beats manual __disable_irq()/__enable_irq() pairs in three ways: the re-enable can't be forgotten or skipped by an early return, since the destructor runs on every exit; it restores the previous PRIMASK state rather than blindly enabling, so it nests correctly (an inner guard won't wrongly re-enable interrupts that an outer guard disabled); and the protected region is scoped by braces, making it visually obvious. The one rule: name the object (CriticalSection cs;), because an unnamed temporary is destroyed immediately and protects nothing.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Constructors, Destructors & RAII

Tie setup to object creation and cleanup to scope exit, so you can't forget to release a lock, disable a clock, or re-enable interrupts. The defining C++ idiom for embedded.

More Constructors, Destructors & RAII questions

Browse all 472 interview questions
Write an RAII guard for a critical section. Why is it better than paired enable/disable calls? | EmbeddedPrep.io