EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 86
C++ RAII for Peripherals
Acquire in the constructor, release in the destructor.
RAII ties a resource to an object's life. A class can enable a chip-select in its constructor and release it in its destructor, so you can never forget to release it, even on early return.
This makes bus locking and critical sections safe and tidy, with no run-time cost beyond a few instructions.
EXAMPLE
class CriticalSection {
public:
CriticalSection() { interrupts_off(); }
~CriticalSection() { interrupts_on(); }
};
void update() {
CriticalSection cs; // interrupts off until the function ends
shared_value++;
}