Implement atomic bit set and clear on a shared flags word.
#include <stdatomic.h>
#include <stdint.h>
#include <stdbool.h>
static _Atomic uint32_t flags;
static inline void flag_set(unsigned n) { atomic_fetch_or_explicit(&flags, 1u << n, memory_order_relaxed); }
static inline void flag_clear(unsigned n) { atomic_fetch_and_explicit(&flags, ~(1u << n), memory_order_relaxed); }
static inline bool flag_test(unsigned n) { return (atomic_load_explicit(&flags, memory_order_relaxed) >> n) & 1u; }
static inline bool flag_test_and_clear(unsigned n)
{
return (atomic_fetch_and_explicit(&flags, ~(1u << n), memory_order_acq_rel) >> n) & 1u;
}
Points: flags |= bit is a non-atomic read-modify-write; C11 atomics compile to an LDREX/STREX retry loop on Cortex-M3+ (or single LDSET/LDCLR instructions on Armv8.1-A). On Cortex-M0/M0+, which lack exclusives, the compiler calls a library helper that disables interrupts; doing that yourself in a tiny critical section is equivalent. For hardware registers, use the peripheral's set/clear registers or bit-banding instead (atomic instructions often do not work on device memory). test_and_clear is the typical "consume an event flag" operation.