A classic that every embedded newcomer meets:
static int done;
void timer_isr(void) {
done = 1;
}
int main(void) {
init();
while (!done) { }
puts("woke up");
}
With optimisation on, the compiler sees that nothing in the loop changes done. As far as the C abstract machine knows, no one else runs, so it loads done once and spins forever on a register. Your interrupt fires, sets the variable, and the program never notices.
Fix: static volatile int done;. volatile tells the compiler every access is observable, so it must reload each time.
What volatile does not give you:
- Atomicity. On an 8-bit AVR, a 16-bit
volatileread is two loads. If the ISR runs between them you read half of an old value and half of a new one. Disable interrupts around the read, or use a one-byte flag. - Ordering against other data. If the ISR writes a buffer and then sets the flag, the compiler is free to move ordinary, non-volatile accesses across the
volatileones, and on bigger chips the CPU and the cache can reorder too. You may need a compiler barrier or a memory barrier. - Thread safety. It is not a mutex. On a multicore part it is not even close.
Rule of thumb: volatile for hardware registers and ISR-shared flags of the natural word size. Everything else needs real synchronisation. Hope remains terminated.