可重入函数
Reentrant Function
你好,在https://www.embedded.com/design/operating-systems/4008268/2/Back-to-the-Basics--Practical-Embedded-Coding-Tips-Part-1的文章中,提到了如何使函数可重入。
long i;
void do_something(void){
disable_interrupts();
i+=0x1234;
enable_interrupts();
}
作者告诉:"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."
我不明白更改机器上下文到底有多危险?有人可以举例说明这可能导致有害后果吗?
请注意,do_something()
既可以从启用中断的地方调用,也可以从已经禁用中断的地方调用。在第二种情况下启用中断以各种危险的方式违背了调用者的期望。
您真正需要的是在禁用中断时保存之前的中断状态,并在之后恢复它。
所以,更好的版本是:
long i;
void do_something(void){
irq_state_t prev_int_state = disable_interrupts_save();
i+=0x1234;
restore_interrupts(prev_int_state);
}
你好,在https://www.embedded.com/design/operating-systems/4008268/2/Back-to-the-Basics--Practical-Embedded-Coding-Tips-Part-1的文章中,提到了如何使函数可重入。
long i;
void do_something(void){
disable_interrupts();
i+=0x1234;
enable_interrupts();
}
作者告诉:"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."
我不明白更改机器上下文到底有多危险?有人可以举例说明这可能导致有害后果吗?
请注意,do_something()
既可以从启用中断的地方调用,也可以从已经禁用中断的地方调用。在第二种情况下启用中断以各种危险的方式违背了调用者的期望。
您真正需要的是在禁用中断时保存之前的中断状态,并在之后恢复它。
所以,更好的版本是:
long i;
void do_something(void){
irq_state_t prev_int_state = disable_interrupts_save();
i+=0x1234;
restore_interrupts(prev_int_state);
}