0 day streak
c / intermediate
Snippet

Atomic Operations with stdatomic.h

The stdatomic.h header (C11) provides types and functions for atomic operations, which are essential for thread-safe programming without the overhead of heavy locks. These operations are guaranteed to be completed in a single step without interruption, preventing data races in concurrent environments.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <stdatomic.h>
int main() {
_Atomic int counter = 0;
// Atomically increments the value
atomic_fetch_add(&counter, 1);
// Atomically exchanges values
int old_val = atomic_exchange(&counter, 10);
printf("Old: %d, New: %d\n", old_val, counter);
return 0;
}
Breakdown
1
_Atomic int counter = 0;
Declares an integer that will be accessed using atomic operations.
2
atomic_fetch_add(&counter, 1);
Increments the counter safely, returning the previous value.
3
atomic_exchange(&counter, 10);
Sets the counter to a new value and returns the old value as an atomic action.