0 day streak
c / expert
Snippet

Atomic Compare-and-Swap (CAS) with stdatomic.h

Uses C11's stdatomic.h to perform a lock-free update. atomic_compare_exchange_weak checks if the current value matches 'expected'; if so, it updates it to 'desired'. If not, it updates 'expected' with the actual current value, allowing for a retry loop.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
#include <stdatomic.h>
#include <stdbool.h>
void safe_update(atomic_int *val) {
int expected = atomic_load(val);
int desired;
do {
desired = expected + 1;
} while (!atomic_compare_exchange_weak(val, &expected, desired));
}
Breakdown
1
atomic_int *val
Declaration of an atomic integer type ensuring thread-safe access.
2
atomic_compare_exchange_weak
Atomically compares the object with expected and replaces it with desired if equal.