Let x
and y
be variables that are shared between main code and interrupt code.
My idea of volatile
is that it is only and always needed for hardware variables and interrupt variables that are also used in main code.
Every usage of x
and y
in the main code is guaranteed to be atomic by disabling interrupts.
Do x
and y
really need to be volatile
, or is it enough to put a memory barrier before using them to force reloading the variables from RAM?
A)
volatile bool x;
volatile int y[100];
int main(void)
{
while (true) {
disable_interrupts();
if (x)
work(y);
x = false;
enable_interrupts();
}
}
B)
bool x;
int y[100];
int main(void)
{
while (true) {
memory_barrier();
disable_interrupts();
if (x)
work(y);
x = false;
enable_interrupts();
}
}
The objectives are:
To let the compiler optimize
work()
.Be able to use standard library functions such as
memcpy()
(those aren't made to be used withvolatile
variables).
Edit: add interrupt example
interrupts.c
:
extern volatile? int x;
extern volatile? int y;
void interrupt(void)
{
x = true;
REGY1 = y[7];
y[23] = REGY2;
}
work
gets inlined? And who exactly updates the variables? – CamposMy idea of volatile
nee, only when the compiler optimizes them out. You don't need to volatile all variables, only those you don't want to apply optimizations to.those aren't made to be used with volatile variables
- accessing volatile object via non-volatile handle is UB anyway. Anyway, compiler should not optimize thememcpy
, as it will see it accesses a volatile object. Let's mark it: should.is it enough to put a memory barrier
- no it is not. In your second code snippet compiler will completely removeif (x)
statement as it isif (false)
. – Calvadosvolatile
... behaviour undefined. – Glucoproteinif(x)
: Why? The compiler can't make that assumption after a memory barrier, right? – HauteurREGY1
andREGY2
would bevolatile
; hardware always needs it. My question was specifically for variables that don't represent any hardware. – Hauteurvolatile
and memory barriers do the same thing, tell the compiler that something could have been changed in memory, forcing a paricular ordering of variable accesses. They just do it on different set of accesses. – Wardlawvolatile
, right? – Hauteurvolatile
access as a memory barrier, but that's another story. – Camposvolatile
qualify variables shared with a callback, because as a compiler extension, the compiler ensures that it realizes that those variables may be updated at any point. But this is by no means guaranteed by any standard. – Campos