小编che*_*ind的帖子

使用临时volatile限定符优化共享阵列访问

我想知道在以下情况下,临时volatile限定符是否会产生正确的行为.假设ISR收集数组中的值,并且一旦收集到足够的值,它就表示准备就绪.

int array[10]; // observe no volatile here
int idx = 0;   // neither here
volatile bool ready = false; // but here
Run Code Online (Sandbox Code Playgroud)

这里的ISR是伪代码

ISR() {
  if (idx < 10)
     array[idx++] = ...;
  ready = (idx >= 10);
}
Run Code Online (Sandbox Code Playgroud)

假设我们可以保证array将是只读 ready发出信号,和元素是通过特定的方法来访问:

int read(int idx) {
  // temporary volatile semantics
  volatile int *e = (volatile int*)(array + idx);
  return *e;
}
Run Code Online (Sandbox Code Playgroud)

这似乎是根据cpp-reference允许的

向volatile类型转换非易失性值无效.要使用易失性语义访问非易失性对象,必须将其地址强制转换为指向易失性的指针,然后必须通过该指针进行访问.

为了完整起见,主程序执行以下操作

void loop() {
   if (ready) {
     int …
Run Code Online (Sandbox Code Playgroud)

c c++ volatile isr compiler-optimization

6
推荐指数
1
解决办法
119
查看次数

标签 统计

c ×1

c++ ×1

compiler-optimization ×1

isr ×1

volatile ×1