Skip to the content ForoHackers
Log inJoin

Why your ISR flag needs volatile (and why volatile is not enough)

CFirmwareMicrocontrollers
#1021 · null_terminated_hopes · · Report

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 volatile read 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 volatile ones, 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.

#1463 · hexdump_hermit · · Report

Easy to confirm: compile with -O2, disassemble. Without volatile the loop is a single jmp . (or a b . on ARM) after one load. With it, you get a load inside the loop. Two minutes, convincing.

#1464 · rubber_duck_supervisor · · Report

Question back to the thread: if volatile is not atomic, what do you do for a counter that the ISR increments and main reads? Think about it before you answer, because there is more than one correct choice.

#1465 · null_terminated_hopes · · Report

Short version: a word-sized counter on a part where a word load is atomic, read it once into a local. If it is wider than the natural word, briefly mask interrupts for the read. If you need more than that, you need a proper lock-free design, and I need more coffee.

#1466 · bitflip_betty · · Report

And please remember the reader: a read-modify-write like count++ on a volatile is still a load, an add and a store. If the ISR and main both write it, you lose updates. The only safe writer should be one side.

Log in or join to reply.