[英]volatile vs memory barrier for interrupts
Let x
and y
be variables that are shared between main code and interrupt code. 设x
和y
是主代码和中断代码之间共享的变量。
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. 我对volatile
是,只有并且总是需要硬件变量和中断变量,这些变量也在主代码中使用。
Every usage of x
and y
in the main code is guaranteed to be atomic by disabling interrupts. 通过禁用中断,主代码中x
和y
每次使用都保证是原子的。
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? x
和y
确实需要是volatile
,还是在使用它们强制从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) B)
bool x;
int y[100];
int main(void)
{
while (true) {
memory_barrier();
disable_interrupts();
if (x)
work(y);
x = false;
enable_interrupts();
}
}
The objectives are: 目标是:
To let the compiler optimize work()
. 让编译器优化work()
。
Be able to use standard library functions such as memcpy()
(those aren't made to be used with volatile
variables). 能够使用标准库函数,例如memcpy()
(不能与volatile
变量一起使用)。
Edit: add interrupt example 编辑:添加中断示例
interrupts.c
: interrupts.c
:
extern volatile? int x;
extern volatile? int y;
void interrupt(void)
{
x = true;
REGY1 = y[7];
y[23] = REGY2;
}
Memory barriers instead of volatile
are fine. 内存障碍而volatile
很好。 Linux kernel developers prefer it that way Linux内核开发人员更喜欢这种方式
There are a few things to watch out for. 有几点需要注意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.