Atomic fetch and add
What you'll learn: How to safely increment shared variables across multiple threads without using heavy locks.
The Race Condition Problem
Imagine two people are sharing a single notebook to keep track of a tally. Both see the current number is 10. Simultaneously, they both decide to add 1, write down 11, and close the book. Even though two people added to the total, the result is 11 instead of 12. This is a classic "race condition" in multithreading.
In standard C, counter++ actually performs three steps: load the value, add one, and store it back. If another thread sneaks in between those steps, your data gets corrupted.
The Atomic Solution
To fix this without the "heavy lifting" of a mutex (which is like putting the notebook in a locked safe), we use Atomic Fetch and Add.
Think of this as an automated stamp. Instead of reading, thinking, and writing, you press a button that instantly increments the counter and hands you back the value it had just before the change. This entire operation is "atomic," meaning it happens in one indivisible heartbeat. No other thread can interrupt the process midway.
Using atomic_fetch_add
In C11, we use the <stdatomic.h> library. The function atomic_fetch_add takes a pointer to an atomic variable and the value you want to add.
#include <stdio.h>
#include <stdatomic.h>
#include <threads.h>
// Define an atomic integer
atomic_int global_counter = 0;
int increment_task(void* arg) {
for (int i = 0; i < 1000; i++) {
// Adds 1 to global_counter and returns the previous value
// This is thread-safe!
atomic_fetch_add(&global_counter, 1);
}
return 0;
}
int main() {
thrd_t t1, t2;
thrd_create(&t1, increment_task, NULL);
thrd_create(&t2, increment_task, NULL);
thrd_join(t1, NULL);
thrd_join(t2, NULL);
printf("Final count: %d\n", global_counter); // Always 2000
return 0;
}
Why it matters
The "Fetch" part of atomic_fetch_add is useful because it returns the old value. If you need to know exactly which "ticket number" your thread just grabbed while incrementing a queue, this function gives it to you reliably. It is significantly faster than using a mutex because it uses specialized CPU instructions designed for high-speed synchronization.
Key takeaway
atomic_fetch_add allows multiple threads to update a shared counter simultaneously and safely without the performance overhead of traditional locks.