我什么时候需要在 ISR 中使用 volatile? [英] When do I need to use volatile in ISRs?

查看:49
本文介绍了我什么时候需要在 ISR 中使用 volatile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作嵌入式固件,其中初始化后的一切都发生在 ISR 中.我有它们之间共享的变量,我想知道在哪些情况下它们需要可变.我从不阻塞,等待另一个 ISR 的变化.

I am making embedded firmware where everything after initialization happens in ISRs. I have variables that are shared between them, and I am wondering in which cases they need to be volatile. I never block, waiting for a change in another ISR.

我什么时候可以确定在不使用 volatile 时读取或写入实际内存?每个 ISR 一次?

When can I be certain that actual memory is read or written to when not using volatile? Once every ISR?

附录:
这是针对 ARM Cortex-M0 的,但这并不是关于 ISR 的问题,而是关于编译器优化的问题,因此,平台不应该真的很重要.

Addendum:
This is for ARM Cortex-M0, but this isn't really a question about ISRs as much as it is about compiler optimization, and as such, the platform shouldn't really be important.

推荐答案

这个问题完全可以回答,答案很简单:

The question is entirely answerable, and the answer is simple:

如果没有 volatile,您(简单地)不能假设实际的内存访问永远会发生 - 编译器可以自由地得出结论,结果要么完全未使用(如果这在它可以看到的情况下很明显)),或者它们可以安全地缓存在寄存器中,或者乱序计算(只要保持可见依赖项).

Without volatile you (simplistically) can't assume that actual memory access will ever happen - the compiler is free to conclude that results are either entirely unused (if that is apparent in what it can see), or that they may be safely cached in a register, or computed out of order (as long as visible dependencies are maintained).

您需要 volatile 来告诉编译器访问的副作用可能对优化器无法分析的东西很重要,例如中断上下文或不同线程"的上下文.

You need volatile to tell the compiler that the side effects of access may be important to something the optimizer is unable to analyze, such as an interrupt context or the context of a different "thread".

实际上 volatile 是你对编译器说的我知道一些你不知道的东西,所以不要试图在这里聪明"

In effect volatile is how you say to the compiler "I know something you don't, so don't try to be clever here"

请注意 volatile 保证读-修改-写的原子性,甚至不能保证数据类型(或其未对齐)需要多步访问的单独读或写的原子性.在这些情况下,您冒的风险不仅是获得一个过时的值,而且是一个完全错误的值.

Beware that volatile does not guarantee atomicity of read-modify-write, or of even read or write alone where the data type (or its misalignment) requires muti-step access. In those cases, you risk not just getting a stale value, but an entirely erroneous one.

这篇关于我什么时候需要在 ISR 中使用 volatile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆