c / expert
Snippet
Lock-Free Task Synchronization using C11 Atomic Flag Primitives
This snippet illustrates lock-free hardware synchronization using C11 stdatomic.h. Using atomic_flag_test_and_set_explicit with acquire memory ordering ensures safe non-blocking exclusivity without operating system mutex lock overhead.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdatomic.h>#include <stdbool.h>typedef struct {atomic_flag flag;int payload;} ConcurrentBuffer;void buffer_init(ConcurrentBuffer *cb) {atomic_flag_clear(&cb->flag);cb->payload = 0;}bool try_acquire_and_write(ConcurrentBuffer *cb, int data) {if (!atomic_flag_test_and_set_explicit(&cb->flag, memory_order_acquire)) {cb->payload = data;atomic_flag_clear_explicit(&cb->flag, memory_order_release);return true;}return false;}
Breakdown
1
atomic_flag flag;
Declares a guaranteed lock-free boolean atomic state flag primitive.
2
atomic_flag_clear(&cb->flag);
Initializes the atomic flag to the cleared (unlocked) state.
3
if (!atomic_flag_test_and_set_explicit(&cb->flag, memory_order_acquire)) {
Atomically sets flag while acquiring acquire memory barrier visibility to guard critical write.
4
atomic_flag_clear_explicit(&cb->flag, memory_order_release);
Releases ownership atomically with release memory ordering semantics to flush changes.