简体   繁体   English

中断的易失性与内存屏障

[英]volatile vs memory barrier for interrupts

Let x and y be variables that are shared between main code and interrupt code. xy是主代码和中断代码之间共享的变量。

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. 通过禁用中断,主代码中xy每次使用都保证是原子的。

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? xy确实需要是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. 有几点需要注意。

  • Move the barrier after disabling interrupts. 禁用中断后移动屏障。 Interrupts tend to happen at the worst times. 中断往往发生在最糟糕的时候。
  • You need a second memory barrier before enabling interrupts, for variables that are written in the main program, and read in the interupt handler. 在启用中断之前,需要第二个内存屏障,对于在主程序中写入的变量,以及在中断处理程序中读取的变量。
  • Disabling interrupts is not enough in a multiprocessor/multicore system, it doesn't prevent another core from running. 在多处理器/多核系统中禁用中断是不够的,它不会阻止另一个内核运行。
  • Needless to say, interrupts should not be disabled for extended periods of time, as it can prevent some hardware drivers from functioning. 不用说,中断不应该长时间禁用,因为它可能会阻止某些硬件驱动程序运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM