c / expert
Snippet
Atomic Compare-and-Swap State Transitions with Sequentially Consistent Ordering
C11 stdatomic.h provides lock-free concurrency primitives. The atomic_compare_exchange_strong_explicit function atomically updates a state variable only if its current value matches the expected value, using sequential consistency for success and relaxed ordering on failure.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdatomic.h>#include <stdbool.h>typedef enum { STATE_IDLE, STATE_BUSY, STATE_DONE } State;bool transition_state(_Atomic State *current, State expected, State desired) {return atomic_compare_exchange_strong_explicit(current,&expected,desired,memory_order_seq_cst,memory_order_relaxed);}
Breakdown
1
bool transition_state(_Atomic State *current, State expected, State desired) {
Defines a thread-safe state transition function accepting an atomic pointer.
2
return atomic_compare_exchange_strong_explicit(
Invokes explicit compare-and-swap primitive preventing spurious failures.
3
memory_order_seq_cst, memory_order_relaxed
Enforces strict memory barriers on successful CAS while relaxing constraints on mismatch.