Introduction to <stdatomic.h>
What you'll learn: How to prevent data races by using atomic types to ensure simple operations are completed without interruption.
The Problem: The "Interrupted" Counter
Imagine two people are sharing a notebook to count cars passing by. Both see a car at the same time. They both look at the current number (say, 10), add one in their heads (11), and then try to write "11" in the book. Because they acted simultaneously, the book says 11 instead of 12. One count was lost.
In C, a standard integer operation like count++ isn't actually one step; the CPU must read the value, modify it, and write it back. In a multi-threaded program, another thread can jump in halfway through this process, causing a "data race."
The Solution: Atomic Operations
Introduced in C11, the <stdatomic.h> library provides a way to make these operations atomic. The word "atomic" comes from the Greek atomos, meaning "indivisible." An atomic operation happens all at once or not at all. No other thread can see the variable in a halfway-done state.
When you use an atomic type, the compiler and the CPU work together to lock the clubhouse door while the variable is being updated. Other threads must wait their turn, ensuring no counts are ever lost.
Using _Atomic
To use atomics, you prefix your variable type with the _Atomic keyword (or use the atomic_int alias).
#include <stdio.h>
#include <stdatomic.h>
int main(void) {
// This integer is now thread-safe for simple operations
atomic_int shared_counter = 0;
// Even if 100 threads did this at once,
// the result would be exactly 2.
atomic_fetch_add(&shared_counter, 1);
atomic_fetch_add(&shared_counter, 1);
printf("Final count: %d\n", shared_counter);
return 0;
}
Why not use this for everything?
Atomic operations are slightly slower than regular variables because they require coordination at the hardware level. You should use them specifically for shared flags, counters, or state indicators that multiple threads need to access at the same time.
Key takeaway
Atomic types ensure that simple operations like incrementing a variable are treated as a single, uninterruptible unit, preventing data corruption in multi-threaded programs.