CKTIS / C
call_once — C23 library function
`call_once(flag, func)` uses a `once_flag` to call `func` exactly once—the first effective call with that flag object—and returns no value. Completion of the effective call synchronizes with every other call using the same flag: callers already in progress and waiting for `func`, as well as later callers.
Version: C23
Syntax
void call_once(once_flag *flag, void (*func)(void));call_once(flag, func) uses a once_flag to call func exactly once—the first effective call with that flag object—and returns no value. Completion of the effective call synchronizes with every other call using the same flag: callers already in progress and waiting for func, as well as later callers.
Use it for safe lazy initialization of shared state. The example starts two threads and both call call_once, but the initializer increments its counter only once and publishes value = 42; after joining, the result is 1 42.
The flag must be initialized with ONCE_FLAG_INIT and remain the same object for the whole protocol; do not copy or try to reset it. func has type void(void), and call_once has no error result. An implementation defining __STDC_NO_THREADS__ may omit <threads.h>, and recursively using the same flag is not a portable protocol.
Examples
#include <stdio.h>
#include <threads.h>
static once_flag initialization_flag = ONCE_FLAG_INIT;
static int initialization_count;
static int shared_value;
static void initialize_shared_value(void) {
++initialization_count;
shared_value = 42;
}
static int worker(void *unused) {
(void)unused;
call_once(&initialization_flag, initialize_shared_value);
return 0;
}
int main(void) {
thrd_t first;
thrd_t second;
if (thrd_create(&first, worker, NULL) != thrd_success) return 1;
if (thrd_create(&second, worker, NULL) != thrd_success) {
thrd_join(first, NULL);
return 1;
}
thrd_join(first, NULL);
thrd_join(second, NULL);
printf("%d %d\n", initialization_count, shared_value);
return 0;
}
Result
1 42
Use it for safe lazy initialization of shared state. The example starts two threads and both call `call_once`, but the initializer increments its counter only once and publishes `value = 42`; after joining, the result is `1 42`.