Optimization of access to distributed arrays with a temporary volatile qualifier

I was wondering if in the following scenario the temporary mutable classifier would give the correct behavior. Suppose ISR collects values ​​in an array, and as soon as a sufficient number of 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 ISR is pseudo code

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

Suppose that we guarantee that an array will only be considered after ready is signaled, and the elements will be accessible through a specific method only >:

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

which is apparently resolved according to cpp-reference

Casting a non-volatile value to a volatile type does not affect. To access a non-volatile object using volatile semantics, its address must be translated into a pointer to volatile, and then access must be made through this pointer.

To complete the main procedure, the following

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

In this scenario, should I expect to read the correct values ​​from array or will it be volatile for the elements of the array needed to ensure that writing to the array from ISR() is actually performed in RAM?

Note that Why volatility is required in C? , does not indicate whether volatile is required in this special case.

+6
source share
1 answer

writing to array[] not through volatile , so you cannot rely on this to be observable behavior. Yes, the compiler should produce an uncached array reading, but this is only half the image.

You talk about order as if it were affected by volatile - it is not.

+1
source

Source: https://habr.com/ru/post/1011801/


All Articles