易失性vs内存屏障的中断 [英] volatile vs memory barrier for interrupts
问题描述
让x
和y
是在主代码和中断代码之间共享的变量.
Let x
and y
be variables that are shared between main code and interrupt code.
我对volatile
的想法是,对于并且也在主代码中使用的硬件变量和中断变量,它始终是唯一需要的.
My idea of volatile
is that it is only and always needed for hardware variables and interrupt variables that are also used in main code.
通过禁用中断,可以保证主代码中x
和y
的每种用法都是原子的.
Every usage of x
and y
in the main code is guaranteed to be atomic by disabling interrupts.
x
和y
确实需要为volatile
,还是在使用它们强制从RAM重新加载变量之前放置内存屏障是否足够?
Do x
and y
really need to be volatile
, or is it enough to put a memory barrier before using them to force reloading the variables from RAM?
A)
volatile bool x;
volatile int y[100];
int main(void)
{
while (true) {
disable_interrupts();
if (x)
work(y);
x = false;
enable_interrupts();
}
}
B)
bool x;
int y[100];
int main(void)
{
while (true) {
memory_barrier();
disable_interrupts();
if (x)
work(y);
x = false;
enable_interrupts();
}
}
目标是:
-
让编译器优化
work()
.
能够使用标准库函数,例如memcpy()
(这些库函数不能与volatile
变量一起使用).
Be able to use standard library functions such as memcpy()
(those aren't made to be used with volatile
variables).
添加中断示例
interrupts.c
:
extern volatile? int x;
extern volatile? int y;
void interrupt(void)
{
x = true;
REGY1 = y[7];
y[23] = REGY2;
}
推荐答案
使用内存屏障代替volatile
很好. Linux内核开发人员那样优先
Memory barriers instead of volatile
are fine. Linux kernel developers prefer it that way
有一些需要注意的地方.
There are a few things to watch out for.
- 在禁用中断后移动屏障.中断往往发生在最坏的时候.
- 对于在主程序中写入并在中断处理程序中读取的变量,在启用中断之前,您需要第二个内存屏障.
- 在多处理器/多核系统中禁用中断是不够的,它不会阻止另一个核运行.
- 不用说,不应长时间禁用中断,因为它会阻止某些硬件驱动程序运行.
这篇关于易失性vs内存屏障的中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!