Implement an atomic increment.
#include <stdatomic.h>
#include <stdint.h>
static _Atomic uint32_t counter;
uint32_t atomic_inc(void)
{
return atomic_fetch_add_explicit(&counter, 1u, memory_order_relaxed) + 1u; /* returns new value */
}
/* the same thing with an explicit compare-and-swap loop */
uint32_t atomic_inc_cas(_Atomic uint32_t *p)
{
uint32_t old = atomic_load_explicit(p, memory_order_relaxed);
while (!atomic_compare_exchange_weak_explicit(p, &old, old + 1u,
memory_order_relaxed, memory_order_relaxed)) {
/* old now holds the current value; retry */
}
return old + 1u;
}
Points: count++ on a plain or volatile variable is load–add–store and loses updates under concurrency. Atomic RMW operations compile to LDREX/STREX retry loops on Cortex-M3+ and Armv8.0-A, or to a single LDADD with Armv8.1 LSE atomics. Relaxed ordering is enough for a pure statistics counter; use acquire/release when the counter also signals that other data is ready. On Cortex-M0 (no exclusives) atomics are implemented by briefly disabling interrupts.