Search code examples
c++ccompiler-optimizationvolatileisr

Optimizing shared array access with temporary volatile qualifier


I was wondering if in the following scenario a temporary volatile qualifier would yield correct behavior. Assume an ISR collects values in an array and once enough values have been collected it signals readiness.

int array[10]; // observe no volatile here
int idx = 0;   // neither here
volatile bool ready = false; // but here

Here's the ISR is pseudo-code

ISR() {
  if (idx < 10)
     array[idx++] = ...;
  ready = (idx >= 10);
}

Assume we can guarantee that array will be read only after ready is signalled, and elements are accessed via specific method only:

int read(int idx) {
  // temporary volatile semantics
  volatile int *e = (volatile int*)(array + idx);
  return *e;
}

which seems to be allowed according to 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.

For completeness the main routine does the following

void loop() {
   if (ready) {
     int val = read(0); // Read value 
     // do something with val.
   }
}

In such a scenario should I expect to read correct values from array or is volatile on the array elements required to guarantee that writing to the array from within ISR() is actually performed in RAM?

Note that Why is volatile needed in C? does not detail whether or not in this special case volatile is needed.


Solution

  • The write to array[] is not through volatile, so you can't rely on that being observable behavior. Yes, the compiler must issue a non-cached read of array, but that is only half of the picture.

    You're talking about order as if that's affected by volatile - it isn't.