c++ - 使用临时 volatile 限定符优化共享数组访问

标签 c++ c compiler-optimization volatile isr

我想知道在以下情况下临时的 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。

最佳答案

writearray[] 不是通过 volatile,所以你不能依赖它是可观察的行为。是的,编译器必须发出对 array 的非缓存读取,但这只是图片的一半。

你在谈论顺序,就好像它受到了volatile的影响——事实并非如此。

关于c++ - 使用临时 volatile 限定符优化共享数组访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40301542/

相关文章:

c++ - 是否可以将函数(指针?)保存到对象中?

c++ - undefined reference 错误c++

c - 初始化数组的段错误

c - 为什么 `printf("%s", "foo")` not being optimized to ` fputs ("foo", stdout)`?

c++ - 如何编写比三值比较函数更整洁的 operator() 或 less-than-functor

c++ - 在常量表达式中除以零

c++ - 在 'for' 循环中递增 1 时使用 > (<) 而不是 != 是否有技术原因?

c - 添加来自 3 个不同 CSV 列的数字

c++ - 将 "-march=native"intel 编译器标志添加到编译行会导致 KNL 上出现浮点异常

c++ - 如何有条件地为模板头设置编译器优化