c / expert
Snippet
Lock-Free State Transition Using C11 Atomic Compare-Exchange
In high-performance concurrent C systems, mutexes introduce thread blocking overhead. C11 atomic primitives like atomic_compare_exchange_strong allow lock-free state updates by comparing the memory contents with an expected value and updating it to a new value atomically.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdatomic.h>#include <stdbool.h>#include <stdio.h>typedef enum { STATE_IDLE, STATE_BUSY, STATE_DONE } MachineState;bool try_transition(_Atomic MachineState *state, MachineState expected, MachineState next) {return atomic_compare_exchange_strong(state, &expected, next);}int main(void) {_Atomic MachineState current = STATE_IDLE;if (try_transition(¤t, STATE_IDLE, STATE_BUSY)) {printf("State successfully transitioned to BUSY.\n");}return 0;}
Breakdown
1
_Atomic MachineState *state
Qualifies the state variable as an atomic type to prevent data races during concurrent read/write operations.
2
atomic_compare_exchange_strong(state, &expected, next)
Atomically updates *state to next if it equals *expected; otherwise updates *expected to the current value of *state.