Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Interrupts and Timers

Volatile, Atomicity and Shared Data in Interrupts

Learn why shared variables need volatile, how torn reads happen, how critical sections protect multi-byte data, and how to build a lock-free ring buffer between an ISR and main.

An interrupt service routine and the main loop run on the same CPU but behave like two separate threads that can interrupt each other at any instruction. As soon as both touch the same variable, three problems appear: the compiler may not believe the variable can change, a multi-byte value may be read half-updated, and a sequence like "read, modify, write" may be split in the middle. These are the classic causes of embedded bugs that happen once an hour and vanish under a debugger.

In this lesson you will learn what volatile does and what it does not do, how to make multi-byte access safe with a critical section, and how to build the most useful structure for passing data from an ISR to the main loop: the ring buffer.

What volatile means

The compiler assumes that a normal variable only changes when your code changes it. So it is allowed to keep the value in a register and skip repeated reads. That is a harmless optimization in ordinary programs, and a disaster here:

C
static int done;                 // set by an ISR

void wait_for_done(void) {
    while (!done) { }            // compiler may read 'done' once and loop forever
}

With optimization on, the compiler sees nothing in the loop that modifies done, loads it once and turns the loop into an infinite jump. Marking the variable volatile tells the compiler that every read and write is observable: it must perform each access exactly as written, in order, and may not cache or remove them.

C
static volatile int done;        // now each loop iteration really reads memory

Use volatile for:

  • variables written by an ISR and read by main (or the other way round);
  • memory-mapped hardware registers (see the chapter on registers and peripherals);
  • variables changed by another core, DMA, or any other agent the compiler cannot see.

What volatile does not do

volatile is not a lock and does not make anything atomic. Three limits matter:

  1. No atomicity. volatile uint32_t t; t++; on an 8-bit or 16-bit CPU becomes several instructions (load, add, store). An interrupt can strike in the middle.
  2. No ordering between different variables on weak-memory hardware. On simple single-core microcontrollers this rarely bites, but on multi-core chips or with write buffers you need memory barriers.
  3. No protection for read-modify-write. flags |= 0x01; in main and flags |= 0x02; in an ISR can still lose one update, because each statement is a load, an or, and a store.

Torn reads

On an 8-bit CPU a 16-bit counter lives in two bytes, and reading it takes two instructions. If the timer ISR increments the counter between those two reads, you get a value that never existed. The simulation below holds a 16-bit counter as two bytes. A tick event arrives right between reading the low byte and the high byte. In the safe version the read happens inside a critical section: interrupts are disabled, so the tick stays pending until the read is done.

C A torn read and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The unsafe read returns 0x01FF, which is off by 255 from either true value. Such an error appears only when the tick lands in a two-instruction window, so tests rarely find it.

The fix is general: protect any multi-byte shared value with a critical section, or use a technique that avoids the problem:

C
// Read-only sketch for Cortex-M: save the interrupt state, disable, restore.
uint32_t primask = __get_PRIMASK();
__disable_irq();
uint32_t copy = shared_counter;        // or update several variables together
__set_PRIMASK(primask);                // restore, do not blindly enable

Restore the previous state instead of unconditionally enabling interrupts, so a critical section inside a function that was itself called with interrupts off does not switch them on by accident. Keep critical sections as short as you can: while interrupts are off, latency grows.

Other safe patterns:

  • Read until stable. Read the value twice and repeat if the two copies differ. No interrupt masking is needed when changes are infrequent.
  • Single writer, single reader. If only the ISR writes a variable and the CPU can read it in one instruction (a native-width aligned word), no lock is needed.
  • Atomic types. C11 <stdatomic.h> gives atomic_uint and friends with guaranteed atomic operations where the hardware supports it. Cortex-M3 and later have exclusive load/store instructions, but cores without them (Cortex-M0, many 8-bit parts) may lack lock-free atomics for read-modify-write.

The ring buffer

The classic way to pass a stream of events from an ISR to main is a circular (ring) buffer: a fixed array plus two indexes. The head is where the producer writes next, and the tail is where the consumer reads next. When an index reaches the end it wraps to the start. The buffer is empty when head == tail and full when advancing head would make it equal to tail. (One slot is sacrificed so "full" and "empty" are distinguishable, so a buffer of size N holds N - 1 items.)

The design is lock-free when exactly one context writes head (the producer) and exactly one writes tail (the consumer). Each side only reads the other's index, and each index is a single, aligned byte or word, so no critical section is needed. If you pick a power-of-two size, wrapping is a cheap bit mask: (i + 1) & (SIZE - 1).

C An ISR-to-main ring buffer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Two details matter on real hardware. First, the producer must write the data before it moves head, because the moment head changes the consumer is allowed to read the new slot. Second, on a core with a cache or write buffer you also need a memory barrier between the two steps. On a simple Cortex-M0 or AVR the order of statements is enough once the indexes are volatile.

Decide in advance what happens on overflow. Dropping new bytes (as above) keeps old data; overwriting the oldest keeps recent data. Either way, count the drops so you notice when the consumer is too slow.

A checklist for shared data

  • Mark every variable shared with an ISR volatile.
  • Make shared flags one byte or one native word so access is atomic.
  • Protect multi-byte values and read-modify-write sequences with a critical section.
  • Restore the old interrupt state instead of always enabling.
  • For streams, use a single-producer, single-consumer ring buffer.
  • Keep the ISR's side of any shared structure as small as possible.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What problem does volatile solve?

    volatile forces every access to really happen, in order. It does not make multi-byte access atomic.
  2. 2. On an 8-bit MCU, main reads a 16-bit volatile counter that an ISR increments. What is the safest approach?

    The 16-bit read takes two instructions, so the ISR could change the value in between. Disabling interrupts briefly prevents the torn read.
  3. 3. In a ring buffer of size 16 with one slot kept empty, how many bytes can it hold?

    Keeping one slot free lets the code tell 'full' (head + 1 == tail) from 'empty' (head == tail), so capacity is size - 1.
  4. 4. Why can a ring buffer need no lock?

    With a single producer owning head and a single consumer owning tail, neither side writes the other's index, so no update is lost.

Summary

  • volatile stops the compiler from optimizing away accesses to variables changed outside normal program flow; it does not give atomicity.
  • Multi-byte values and read-modify-write operations need a critical section, a stable-read loop or atomic instructions.
  • Save and restore the interrupt mask instead of always enabling interrupts.
  • A single-producer, single-consumer ring buffer moves data from an ISR to main safely without locks.

Next: Debouncing and Software Timers