CALL_ONCE(3) Library Functions Manual CALL_ONCE(3)

call_once
calls function exactly once

POSIX Threads Library (libpthread, -lpthread)

#include <threads.h>

void
call_once(once_flag *flag, void (*func)(void));

#define ONCE_FLAG_INIT /* implementation specified */

The call_once function uses the flag parameter to ensure that func is called exactly once, even if called from several threads.

The ONCE_FLAG_INIT definition expands to a value that can be used to initialize an object of type once_flag.

This portable interface is implemented on top of the pthread_once(3) functionality.

None.

The following calls call_once from two threads using the portable thrd(3) interface.
#include <stdio.h>
#include <threads.h>

static once_flag oflag = ONCE_FLAG_INIT;

void
called_once(void)
{
	printf("called once0);
}

int
tfun(void *ptr)
{
	call_once(&oflag, called_once);
}

int
main(int argc, char **argv)
{
	thrd_t th1, th2;

	thrd_create(&th1, tfun, NULL);
	thrd_create(&th2, tfun, NULL);

	thrd_join(th1, NULL);
	thrd_join(th2, NULL);

	return 0;
}

pthread_once(3), threads(3)

The call_once function conforms to ISO/IEC 9899:2011 (“ISO C11”).

This interface first appeared in NetBSD 9.

Kamil Rytarowski <kamil@NetBSD.org>
October 16, 2016 NetBSD 9.0