CKTIS / C
atomic_flag_test_and_set — C23 atomic function
`atomic_flag_test_and_set(object)` from `<stdatomic.h>` atomically sets an `atomic_flag` and returns its previous state: `false` means the call acquired a previously clear flag, while `true` means it was already set.
Version: C23
Syntax
bool atomic_flag_test_and_set(volatile atomic_flag *object);atomic_flag_test_and_set(object) from <stdatomic.h> atomically sets an atomic_flag and returns its previous state: false means the call acquired a previously clear flag, while true means it was already set.
It is the basic primitive for trying to acquire a simple lock. The example really calls it twice on a flag initialized with ATOMIC_FLAG_INIT: the first call returns 0, and the second returns 1 because the flag remains set.
atomic_flag is guaranteed lock-free, but a busy-wait loop can starve threads, consume CPU, and deadlock when reacquired by the same thread. The non-_explicit form uses memory_order_seq_cst; a typical spinlock uses acquire on successful acquisition and release in atomic_flag_clear_explicit. The flag must be initialized and later explicitly cleared.
Examples
#include <stdatomic.h>
#include <stdbool.h>
#include <stdio.h>
int main(void) {
atomic_flag flag = ATOMIC_FLAG_INIT;
bool first = atomic_flag_test_and_set(&flag);
bool second = atomic_flag_test_and_set(&flag);
printf("%d %d\n", first, second);
return 0;
}
Result
0 1
It is the basic primitive for trying to acquire a simple lock. The example really calls it twice on a flag initialized with `ATOMIC_FLAG_INIT`: the first call returns `0`, and the second returns `1` because the flag remains set.