我想知道在以下情况下临时的 volatile 限定符是否会产生正确的行为。假设 ISR 收集数组中的值,一旦收集到足够的值,它就会发出准备就绪的信号。
int array[10]; // observe no volatile here
int idx = 0; // neither here
volatile bool ready = false; // but here
这里的ISR是伪代码
ISR() {
if (idx < 10)
array[idx++] = ...;
ready = (idx >= 10);
}
假设我们可以保证 array
将只在 ready
发出信号并且元素被访问后被读取通过特定方法仅:
int read(int idx) {
// temporary volatile semantics
volatile int *e = (volatile int*)(array + idx);
return *e;
}
这似乎是根据 cpp-reference 允许的
A cast of a non-volatile value to a volatile type has no effect. To access a non-volatile object using volatile semantics, its address must be cast to a pointer-to-volatile and then the access must be made through that pointer.
为了完整起见,主例程执行以下操作
void loop() {
if (ready) {
int val = read(0); // Read value
// do something with val.
}
}
在这种情况下,我应该期望从 array
中读取正确的值,还是在保证从 ISR()
中写入数组所需的数组元素上是易变的实际上是在RAM中执行的?
请注意 Why is volatile needed in C?没有详细说明在这种特殊情况下是否需要 volatile。
最佳答案
write 到 array[]
不是通过 volatile
,所以你不能依赖它是可观察的行为。是的,编译器必须发出对 array
的非缓存读取,但这只是图片的一半。
你在谈论顺序,就好像它受到了volatile
的影响——事实并非如此。
关于c++ - 使用临时 volatile 限定符优化共享数组访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40301542/