Is volatile
needed for a variable that is read&write in main loop, but read-only in ISR?
EDIT: At the moment of writing in main, the ISR is disabled. S
Is volatile needed for a variable that is read&write in main loop, but read-only in ISR?
volatile
is not the issue here, as much as insuring main
loop's writes are not broken apart.
Any changes in main()
without protection from an ISR call, can lead to problems, volatile
or not. Declaring it volatile
does not save code from that issue.
volatile some_type obj;
void ISR() {
foo(obj);
}
int main() {
for (;;) {
// volatile useful here to prevent the assignment from being optimized away.
some_type tmp = bar();
// protect from potential interruption need here.
// Without protection, ISR(),
// doesn't know it is working with a completely written `obj`
obj = tmp;
// release from potential interruption
}
volatile
is useful in both directions, for main()
to know ISR()
may have changed obj
and for main()
to not optimize away assignments.
Yet since ISR()
does not change obj
, so volatile
is not needed.
Declaring obj
atomic
may help - but that is another question.