pthread_once(3thr)pthread_once(3thr)Namepthread_once - Calls an initialization routine executed by one thread,
a single time.
Syntax
#include <pthread.h>
int pthread_once (once_block, init_routine)
pthread_once_t *once_block;
pthread_initroutine_t init_routine;
Arguments
once_block
Address of a record that defines the one-time initialization
code. Each one-time initialization routine must have its own
unique pthread_once_t.
init_routine
Address of a procedure that performs the initialization. This
routine is called only once, regardless of the number of times
it and its associated once_block are passed to pthread_once.
Description
This routine calls an initialization routine executed by one thread, a
single time. This routine allows you to create your own initialization
code that is guaranteed to be run only once, even if called simultane‐
ously by multiple threads or multiple times in the same thread.
For example, a mutex or a per-thread context key must be created
exactly once. Calling pthread_once prevents the code that creates a
mutex or per-thread context from being called by multiple threads.
Without this routine, the execution must be serialized so that only one
thread performs the initialization. Other threads that reach the same
point in the code would be delayed until the first thread is finished.
This routine initializes the control record if it has not been initial‐
ized and then determines if the one-time initialization routine has
executed once. If it has not executed, this routine calls the initial‐
ization routine specified in init_routine. If the one-time initializa‐
tion code has executed once, this routine returns.
The once_block must be declared static (for example, either extern or
static in the C language), and it must be initialized at compile time.
In the C language, using pthread.h or pthread_exc.h, initialize an
once_block using the pthread_once_init macro. In other languages, you
must initialize a pthread_once_t block to a value of three integer
zeroes. In C, that corresponds to:
static pthread_once_t block = {0,0,0};
Return Values
If an error occurs, this routine returns -1. No error values have been
specified. Possible return values are as follows.
Return Error Description
0 Successful comple‐
tion.
-1 [EINVAL] Invalid argument.
pthread_once(3thr)