Implement once-only initialisation.
#include <pthread.h>
#include <stdatomic.h>
/* 1. POSIX */
static pthread_once_t once = PTHREAD_ONCE_INIT;
static void init_tables(void) { /* expensive one-time setup */ }
void use_tables(void) { pthread_once(&once, init_tables); /* ... */ }
/* 2. Hand-rolled with atomics: 0 = not started, 1 = running, 2 = done */
static atomic_int init_state;
void call_once_manual(void (*fn)(void))
{
if (atomic_load_explicit(&init_state, memory_order_acquire) == 2) return; /* fast path */
int expected = 0;
if (atomic_compare_exchange_strong_explicit(&init_state, &expected, 1,
memory_order_acquire, memory_order_acquire)) {
fn(); /* we won: initialise */
atomic_store_explicit(&init_state, 2, memory_order_release);
} else {
while (atomic_load_explicit(&init_state, memory_order_acquire) != 2) { /* wait for the winner */ }
}
}
Points: exactly one thread runs the initialiser and everyone else waits until it has finished (not just started); the release store publishes the initialised data, and the acquire load on the fast path makes it visible. Plain "check a flag, then init" is a race (double-checked locking without atomics is broken). Also available: C11 call_once, C++ static local initialisation (thread-safe since C++11), Linux DO_ONCE. On a bare-metal MCU, do one-time setup before enabling interrupts and starting tasks instead.