Run initialisation exactly once with pthread_once
pthread_once() runs an init function exactly once across all threads in glibc 2.39, and every caller waits until it has finished.
Lazy initialisation of a shared table is easy to get wrong with a plain if (!ready) check, because two threads can both see ready == 0. pthread_once closes that race. Every caller passes the same pthread_once_t, initialised with PTHREAD_ONCE_INIT, and the function runs in exactly one of them. The others block until it returns, so no thread ever sees a half-built table.
#include <pthread.h>
#include <stdio.h>
static pthread_once_t once = PTHREAD_ONCE_INIT;
static int table[4];
static void init_table(void)
{
puts("init_table");
for (int i = 0; i < 4; i++)
table[i] = i * i;
}
static void *worker(void *arg)
{
(void)arg;
pthread_once(&once, init_table);
return NULL;
}
int main(void)
{
pthread_t t[4];
for (int i = 0; i < 4; i++) pthread_create(&t[i], NULL, worker, NULL);
for (int i = 0; i < 4; i++) pthread_join(t[i], NULL);
printf("table[3]=%d\n", table[3]);
return 0;
}init_table
table[3]=9The init function takes no argument, so pass data through a global. If it fails there is no retry: the control is marked done regardless, which is the difference from std::call_once in C++. The function is specified in pthread_once(3p); C11 call_once in <threads.h> has been in glibc since 2.28.