Search code examples
interruptreentrancydisable

Reentrant Function


Hello in the article from https://www.embedded.com/design/operating-systems/4008268/2/Back-to-the-Basics--Practical-Embedded-Coding-Tips-Part-1, there is mention on how to make a function reentrant.

long i; 
void do_something(void){ 
    disable_interrupts();
    i+=0x1234; 
    enable_interrupts();
}

Autor tells: "This solution does not work. If do_something() is a generic routine, perhaps called from many places, and is invoked with interrupts disabled, it returns after turning them back on. The machine's context is changed, probably in a very dangerous manner."

I do not understand exactly how changed the machine's context is dangerous? Could somebody give some example where this could lead to harmful consequences to clarify it?


Solution

  • Note that do_something() can be called both from places where interrupts are enabled, and from places where interrupts are already disabled. Enabling interrupts on the second case goes against the expectations of the caller in a vary dangerous way.

    What you really need is to save the previous state of interrupts while disabling them, and restore it afterwards.

    So, a better version would be:

    long i; 
    void do_something(void){ 
        irq_state_t prev_int_state = disable_interrupts_save();
        i+=0x1234; 
        restore_interrupts(prev_int_state);
    }