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

Atomic load and store

Atomic load and store

What you'll learn: How to read and write variables safely across threads without using heavy locks.

The problem with "normal" variables

In standard C, an operation like x = 10 seems instantaneous. However, at the hardware level, moving data between a CPU register and main memory can be interrupted. If one thread is halfway through writing a large value while another thread tries to read it, the reader might see a "torn" value—a garbled mix of old and new data.

To prevent this, we usually use mutexes. But mutexes are heavy; they put threads to sleep and wake them up, which is overkill if you just want to update a single flag or counter.

Atomic operations: The "All or Nothing" guarantee

The <stdatomic.h> library provides specialized functions for "atomic" loads and stores. In computer science, atomic means "indivisible." When you perform an atomic load or store, the CPU guarantees the operation happens as a single, uninterruptible step. No other thread can see the variable in a partial state.

Think of a normal variable like a large box where you have to place items one by one. Someone could peek inside while you are mid-fill. An atomic variable is like a pressurized airlock: it’s either fully open or fully closed, with no possible middle state.

How to use them

Instead of using the = operator, we use atomic_store and atomic_load. These functions ensure the hardware uses specific CPU instructions that bypass the need for locks while maintaining data integrity.

#include <stdatomic.h>
#include <stdbool.h>

// Declare an atomic integer
atomic_int shared_status = 0;

void update_status(int new_value) {
    // Atomic Store: Safely write a value
    atomic_store(&shared_status, new_value);
}

int read_status() {
    // Atomic Load: Safely read a value
    return atomic_load(&shared_status);
}

Why this matters

Atomic loads and stores are the building blocks of "lock-free" programming. They are significantly faster than mutexes because they don't involve the operating system's scheduler. If you have a simple flag (like is_running) that many threads need to check, an atomic load is the most efficient way to handle it without risking data corruption.

Key takeaway

Atomic loads and stores provide a thread-safe, high-performance way to read and write single variables by guaranteeing the operation cannot be interrupted or seen in a partial state.