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

Atomic types like atomic_int

Atomic types like atomic_int

What you'll learn: How to use C11 atomic types to prevent data races without the complexity of manual locking.

The problem with standard variables

In systems programming, multiple threads often try to update the same variable at the exact same time. Imagine two threads trying to increment a standard int counter. The CPU actually performs three steps: load the value, add one, and store it back. If both threads load the value before either has finished storing it, one increment is "lost." This is a classic data race.

Normally, you would fix this with a Mutex, but locking and unlocking a Mutex just to change one number is slow and cumbersome.

Atomic types to the rescue

C11 introduced the <stdatomic.h> library, which provides special types like atomic_int. When you perform an operation on an atomic_int, the CPU guarantees the operation is atomic—meaning it happens all at once, or not at all. It is impossible for another thread to see the variable in a "half-changed" state.

Think of a standard variable like a shared notebook where two people might try to write on the same line simultaneously, causing a smudge. An atomic variable is like a digital counter button: no matter how many people press it at once, the internal machinery ensures every single click is registered perfectly.

Using atomic_int in code

You declare these types using the atomic_ prefix. Most standard operators (like ++ or +=) are overloaded to work automatically and safely.

#include <stdio.h>
#include <stdatomic.h>
#include <threads.h>

// This variable is safe to access from multiple threads
atomic_int global_counter = 0;

int increment_task(void* arg) {
    for (int i = 0; i < 1000; i++) {
        // The ++ operator on an atomic_int is thread-safe
        global_counter++; 
    }
    return 0;
}

int main() {
    // Conceptually: Start multiple threads running increment_task
    // Even with 10 threads, global_counter will be exactly 10000
    printf("Final count: %d\n", global_counter);
    return 0;
}

Why use them?

Atomic types are "lock-free." They use specialized CPU instructions that are much faster than Mutexes. They are the building blocks for high-performance systems where speed is critical, such as operating system kernels or real-time gaming engines.

Key takeaway

Atomic types like atomic_int ensure that simple operations are thread-safe at the hardware level, preventing data races without the overhead of Mutexes.