[Return to Bookshelf] [Contents] [Previous Section] [Next Section] [Index] [Help]


pthread_once

Calls an initialization routine that can be executed by only one thread, a single time.

Syntax

pthread_once(
             once_block,
             init_routine );
 


Argument Data Type Access

once_block opaque pthread_once_t read init_routine opaque pthread_ read initroutine_t


C Binding

int
pthread_once (
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 simultaneously 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 initialized and then determines if the one-time initialization routine has executed once. If it has not executed, this routine calls the initialization routine specified in init_ routine. If the one-time initialization code has executed once, this routine returns.


Note
If you specify an init_ routine that directly or indirectly results in a recursive call to pthread_once specifying the same init_block argument, the recursive call will result in a deadlock.

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 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 the following:

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 completion. -1 [EINVAL] Invalid argument.



[Return to Bookshelf] [Contents] [Previous Section] [Next Section] [Index] [Help]