United States-English |
|
|
HP-UX Reference > Ppthread_once(3T)Pthread LibraryHP-UX 11i Version 3: February 2007 |
|
NAMEpthread_once() — call an initialization routine only once SYNOPSIS#include <pthread.h> pthread_once_t once_control = PTHREAD_ONCE_INIT; int pthread_once( pthread_once_t *once_control, void (*init_routine)(void) ); Parameters
DESCRIPTIONThe pthread_once() function guarantees that init_routine() is only called one time in an application. This function will use the once_control object to determine if init_routine() has previously been called via pthread_once(). The first time pthread_once() is called with once_control and init_routine() causes init_routine() to be called with no arguments. Subsequent calls to pthread_once() with the same once_control will not cause init_routine() to be called again. When pthread_once() returns, the caller is guaranteed that init_routine() has been called (either just now or via a previous call). The macro PTHREAD_ONCE_INIT is used to statically initialize a once control block. This initialization must be done before calling pthread_once(). pthread_once() is not a cancellation point. However, the caller supplied init_routine() may be a cancellation point. If the thread executing init_routine() is canceled, the once_control argument will be set to a state which indicates that init_routine() has not been called yet (see pthread_cancel(3T)). The next time the pthread_once() function is called with once_control, the init_routine() function will be called. The behavior of pthread_once() is undefined if once_control has automatic storage duration or is not initialized by PTHREAD_ONCE_INIT. RETURN VALUEpthread_once() returns returns the following values:
ERRORSThe following error value is returned by pthread_once() if the corresponding condition is detected.
EXAMPLESSome modules are designed for dynamic initialization, i.e., global initialization is performed when the first function of the module is invoked. In a single-threaded program, this is generally implemented as follows: static int initialized = FALSE; extern void initialize(); if (!initialized) { initialize(); initialized = TRUE; } (Rest of the code after initialization.) For a multithreaded process, a simple initialization flag is not sufficient; the flag must be protected against modification by multiple threads. Consequently, this flag has to be protected by a mutex that has to be initialized only once, and so on. A multithreaded program should use initialization similar to: static pthread_once_t once_control = PTHREAD_ONCE_INIT; extern void initialize(); (void)pthread_once(&once_control, initialize); (Rest of the code after initialization.) |
Printable version | ||
|