![]() |
![]() |
![]() |
Dynamic package initialization
#include <pthread.h> pthread_once_t once_control = PTHREAD_ONCE_INIT; int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) );
libc
The pthread_once() function uses the once-control object once_control to determine whether the initialization routine init_routine should be called. The first call to pthread_once() by any thread in a process, with a given once_control, calls init_routine with no arguments. Subsequent calls of pthread_once() with the same once_control won't call init_routine.
The once-control object once_control must be initialized before use by assigning it the macro PTHREAD_ONCE_INIT.
![]() |
No thread will execute past this function until the init_routine returns. |
This example shows how once initialization can be used to initialize a library; both library_entry_point1() and library_entry_point2() need to initialize the library, but that only needs to happen once.
#include <stdio.h> #include <pthread.h> pthread_once_t once_control = PTHREAD_ONCE_INIT; void library_init( void ) { /* initialize the library */ } void library_entry_point1( void ) { pthread_once( &once_control, library_init ); /* do stuff for library_entry_point1... */ } void library_entry_point2( void ) { pthread_once( &once_control, library_init ); /* do stuff for library_entry_point1... */ }
This initializes the library once; if multiple threads call pthread_once(), only one will actually enter the library_init() function. The other threads will block at the pthread_once() call until library_init() has returned. pthread_once() also ensures that library_init() is only ever called once; subsequent calls to the library entry points will skip the call to library_init().
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |
![]() |
![]() |
![]() |