Course contentsShow
← C
Lesson 1147 of 1,21915. Systems ProgrammingFree lesson

Volatile vs Atomic

Volatile vs Atomic

What you'll learn: The difference between preventing compiler shortcuts with volatile and ensuring thread-safe operations with _Atomic.

The Traffic Camera vs. The Armored Truck

Imagine you are watching a busy intersection.

Using volatile is like a traffic camera. It tells the compiler: "Don't assume you know what’s happening here based on previous frames. Look at the hardware every single time." It prevents the compiler from optimizing away reads or writes to a variable that might change due to hardware or signal handlers.

Using atomic is like an armored truck. It ensures that a delivery (an operation) happens all at once. No one can intercept the truck halfway through or see the money while it’s being moved. It prevents "race conditions" where two threads try to change the same value at the exact same moment.

Volatile: Stop Optimizing!

Normally, if you write x = 10; x = 20; in a row, a smart compiler skips the first line because it seems useless. But if x is a memory-mapped sensor, that first "10" might trigger a physical motor. volatile tells the compiler: "Do not skip any steps. I know it looks redundant, but the outside world is watching."

Atomic: Stop Interruption!

In multi-threaded code, an operation like count++ is actually three steps: Read, Add, Write. If two threads do this at once, they might both read "5" and both write "6," losing a count. An atomic variable ensures those three steps are treated as one inseparable heartbeat.

Seeing the Difference

Here is how they look in practice using C11 standards:

#include <stdatomic.h>

// Volatile: Use for hardware registers or signal handlers.
// The compiler won't "cache" this value in a CPU register.
volatile int sensor_status;

// Atomic: Use for shared data between threads.
// This prevents data races when multiple CPUs access it.
atomic_int shared_counter = 0;

void process_data() {
    // This is thread-safe! Other threads will wait for
    // the read-modify-write cycle to finish.
    shared_counter++; 
    
    // This tells the compiler: "Actually read the memory address
    // for sensor_status, don't just use the last value you saw."
    if (sensor_status == 1) {
        // Do something
    }
}

Key takeaway

Use volatile to prevent compiler optimizations on hardware-related memory, and use _Atomic to prevent data corruption in multi-threaded programs.